i made a class where i create my jtable. I have some issues because when i try to update it, it does not work (nothing happens – i think the way i am trying to update it is wrong?). What am i doing wrong?
class tableClass
{
public Vector rowData = null;
public Vector columnNames = null;
private JTable jTable;
DefaultTableModel model;
public tableClass(JPanel jPanel, Vector rowDataInput, Vector columnNamesInput)
{
rowData = rowDataInput;
columnNames = columnNamesInput;
jTable = new JTable(rowData, columnNames);
jTable.setFillsViewportHeight(true);
JScrollPane jScrollPane = new JScrollPane(jTable);
jScrollPane.setPreferredSize(new Dimension(300, 100));
jPanel.add(jScrollPane,BorderLayout.CENTER);
}
public void updateTable(Vector rowDataInput)
{
rowData = rowDataInput;
model =(DefaultTableModel)jTable.getModel();
model.fireTableDataChanged();
}
}
rowDatais given to the JTable in the constructor. Then inupdateTableyou simply update therowDatafield in yourTableClass. Therefore neither theJTablenor itsTableModelknows anything about your changes. You need to update the table’s model inupdateTable.In other words, when you update
rowDatainupdateTableyou are not updating the samerowDataobject you passed into the JTable in your constructor.The below class is functionally the same as your class. Does this make it clearer why what you’re doing has no effect? You see, rowData is in no way shared by TableClass and the JTable. And it shouldn’t be – you should be updating the TableModel. You can implement your own TableModel and update that object with your changes.
You could change your code as follows to prove that the changes work. Note that i’m not advocating this approach – you should really implement your own TableModel, but simply showing you how to change the underlying model itself and therefore see the changes take place in the JTable on-screen.
EDIT As this answer was accepted, and following comments from @kleopatra and using @Adam’s answer (+1) i’ve update the below code to show how to update the entire data Vector or Vectors in
updateTable. I still would not do it like this in production code, but at least this is functionally correct and closer to the OPs question.As i said, this isn’t a good way to do it, but i’m just trying to show you why what you’re doing is not working. 🙂