Reputation: 79
I have a program which basically creates a JTable and JButton. What I have tried is when I press the button, it saves the data of the JTable into a file. When I press it, it throws me an error:
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();
}
});
}
}
When I run the code throws me a:
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)
How can I fix this?
Upvotes: 0
Views: 1155
Reputation: 8348
class Demo extends AbstractTableModel
Your class Demo
extends AbstractTableModel
, not DefaultTableModel
, so when you cast...
(DefaultTableModel)t.getModel();
...the exception is thrown (DefaultTableModel
is a child class of AbstractTableModel
). Make the appropriate cast to AbstractTableModel
, or just avoid the cast entirely and use the returned TableModel
.
AbstractTableModel model = (AbstractTableModel)t.getModel();
//or just
//TableModel model = t.getModel();
This being said, better to save your row/column data without the need for serialization (eg CSV/tab delim file) for better cross-application compatability.
Upvotes: 1