私は基本的にJTableとJButtonを作成するプログラムを持っています。私が試したことは、ボタンを押すと、JTableのデータをファイルに保存することです。私はそれを押すと、それは私にエラーがスローされます:シリアル化Jtable
class Demo extends AbstractTableModel
{
String[] colum = {"first", "Second", "Third"};
Object[][] rowData = {{"Name", 21, "Garzon"},{"Matew", 31, "Herliya"},{"Paul", 24, "Illonis"}};
@Override
public int getColumnCount()
{
return colum.length;
}
@Override
public int getRowCount()
{
return rowData.length;
}
@Override
public Object getValueAt(int row, int col)
{
return rowData[row][col];
}
public boolean isCellEditable(int row, int col)
{
if(col <3)
{
return true;
}
else
{
return false;
}
}
public void setValueAt(Object value, int row, int col)
{
rowData[row][col] = value;
}
}
public class AbstractTableDemo extends JFrame
{
public AbstractTableDemo()
{
setSize(400, 400);
setLayout(null);
Demo demo = new Demo();
JTable t = new JTable(demo);
t.setModel(demo);
JScrollPane sc = new JScrollPane(t);
sc.setBounds(0, 0, 220, 150);
add(sc);
JButton b = new JButton("save");
b.setBounds(0, 200, 100, 30);
b.addActionListener(new ActionListener() //Right here i implemente a button which takes the dta from jtable to sav it into a file
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
DefaultTableModel model = (DefaultTableModel)t.getModel();
ObjectOutputStream fileOut = new ObjectOutputStream(new FileOutputStream("C:/Users/Harry/Desktop/clients.txt"));
fileOut.writeObject(model);
fileOut.close();
System.out.println("Write done");
} catch (IOException e1)
{
e1.printStackTrace();
}
}
});
add(b);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new AbstractTableDemo();
}
});
}
}
私が実行すると、コードは私スロー:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: Demo cannot be cast to javax.swing.table.DefaultTableModel
at AbstractTableDemo$1.actionPerformed(AbstractTableDemo.java:87)
私はこの問題を解決するにはどうすればよいですか?
あなたのクラスは 'DefaultTableModel'ではなく' AbstractTableModel'を拡張しています。 – copeg
@copegはい、それは私の目標です、DefaultTableModelよりも、そのメソッドを使用するようにAbstractTableModelを拡張します – Cohen