Search code examples
javaswingjtableabstracttablemodel

Java: Display two different JTables which are created from the same AbstractTableModel


I have a problem in the display of two different JTables which are created by the same AbstractTableModel. I don't really think that is important to show the code of the AbstractTableModel, but if I am asked for I may present it as well.

I just call two times the same class that extends this AbstractTableModel for two arraylists that I am using to create the tables.

final SwitchTableModel model = new SwitchTableModel(user_decide);
final SwitchTableModel model1 = new SwitchTableModel(duplicates);
JTable table = new JTable(model);
JTable table1 = new JTable(model1);

JFrame frame = new JFrame ("Results");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel grid = new JPanel();
grid.add(toolbar);
grid.add(toolbar1);
grid.add(table);
grid.add(table1);
frame.add(grid);
frame.pack();
frame.setVisible(true);

I also create the toolbars which are the same, I also think that this is irrelevant, that is why I don't post the code - I would do it if you think it is needed.

The problem is that in the end I see the same JTable two times, so I suppose it has something to do with the way that I call the class.


Solution

  • The problem comes from an inappropriate static keyword.:

    public static int [][] data;
    

    static means that the value of that variable will be the same for all your instances. Instead, put your data inside your SwitchTableModel and don't make it static. This will solve your issues immediately.

    Something like:

    public class SwitchTableModel extends AbstractTableModel {
        private int[][] data;
        //... the rest of your current code.
    }