Reputation: 838
My JTable is declared as so:
String[] cols = {"Name","Location"};
String[][] data = new String[][] {{"Name","Location"}};
JTable table = new JTable(data, cols);
So i came across a problem when trying to update my JTable
's data... I'm suppose to be adding a new row to the table. Here is my code for that:
data = new String[][] {{"Name","Location"}{"Name1","Location1"}};
DefaultTableModel dm = (DefaultTableModel)(table.getModel());
dm.fireTableDataChanged();
For some reason i get an error on the Line:
DefaultTableModel dm = (DefaultTableModel)(table.getModel());
The error shown is...
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JTable$1 cannot be cast to javax.swing.table.DefaultTableModel
at client.pages.ClientPage.update(ClientPage.java:171)
Line 171 of my ClientPage.java is the above line of code that i said the error is on.
Anyone know why its doing this?
table.getModel(); //Suppose to return TabelModel not JTable
Upvotes: 0
Views: 7616
Reputation: 28707
table.getModel()
isn't returning a JTable
, it's returning an anonymous class in JTable
that extends TableModel
. Therefore, table.getModel()
is indeed returning the correct class type.
The error occurs, however, because you try to cast this anonymous table model to DefaultTableModel
, which is another subclass of TableModel
, but is not the type being returned by table.getModel()
.
To fix this, simply treat the table model as the interface type TableModel
; don't assume it's a DefaultTableModel
.
Upvotes: 4
Reputation: 347334
Start by taking a look at How to Use Tables and the JavaDocs for DefaultTabelModel
You should change the way you are creating the table and model to something more like...
String[] cols = {"Name","Location"};
String[][] data = new String[][] {{"Name","Location"}};
JTable table = new JTable(new DefaultTableModel(date, cols));
JTable(Object[][], Object[])
actually uses it's own implementation of a the TableModel
Next, change....
data = new String[][] {{"Name","Location"}{"Name1","Location1"}};
DefaultTableModel dm = (DefaultTableModel)(table.getModel());
dm.fireTableDataChanged();
to something more like...
data = new String[][] {{"Name","Location"}{"Name1","Location1"}};
DefaultTableModel dm = (DefaultTableModel)(table.getModel());
dm.fireTableDataChanged();
to something more like...
data = new String[] {"Name1","Location1"};
DefaultTableModel dm = (DefaultTableModel)(table.getModel());
dm.addRow(data);
Upvotes: 3