Remake a JTable by clicking on a JButton
-
15-11-2019 - |
Question
I have a JTable which is 9 by 3 (27 cells), but if the user clicks on a button I want the table to change, being filled with not only new data, but possibly a different number of cells. I am not sure how to do this.
I've tried removing the table from the parent and creating a new instance of the table. Nothing happened. Here:
somepanel.remove(thetable);
JTable newtable = new JTable(datainavector,columntitles);
I want to know how I can either
a) delete a table from a panel and "Put it back in" with a different shape or b)change the contents (and possibly shape) of a table.
Solution
You may wish to change the TableModel of the existing table via the setModel(...) method. Use a DefaultTableModel object with the data of interest and column Strings inserted in it (use the constructor that takes two parameters, a one dimensional array of Object and a two dimensional array of Object).
OTHER TIPS
The only thing missing from your example is to call invalidate()
and repaint()
but I would suggest changing the table model instead:
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Test");
final JTable table = new JTable(generateRandomTableModel());
frame.add(new JScrollPane(table));
frame.add(new JButton(new AbstractAction("Change data") {
@Override
public void actionPerformed(ActionEvent e) {
table.setModel(generateRandomTableModel());
}
}), BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
public static TableModel generateRandomTableModel() {
Random r = new Random();
String[][] data = new String[r.nextInt(10) + 1][r.nextInt(10) + 1];
String[] colNames = new String[data[0].length];
for (int i = 0; i < data[0].length; i++) {
colNames[i] = "" + r.nextInt(100);
for (int j = 0; j < data.length; j++)
data[j][i] = "" + r.nextInt(1000);
}
return new DefaultTableModel(data, colNames);
}
It's OK. I sorted it by creating the new table and setting the old tables visibility to false.