Search code examples
javamodel-view-controllerswingjtabletablemodel

Multiple instances of model components in Java Swing?


Until now I had different model classes for the appropriate Java Swing component, for instance I have several TableModel for several JTable. Every JTable has its own TableModel. The TableModel is based on one object (Model), giving all the required data. Something like this:

public class MyTableModel extends AbstractTableModel {

Model model;

But now I would like to make a change. My interface offers the possibility of multiple instances of Model. So my question is, what should I do?

  • instantiate multiple objects from MyTable
  • change dynamically the current reference to the model upon user interaction

So the basic problem I am facing: I want to use the same JTable with the same TableModel. Should I use multiple TableModel or should I use changing references to the data source?


Similar question:

I want to offer multiple tabs, they change the instance of the underlying model. The do not change the type, but the current instance - meaning, the data changes.

Should I now:

  • instantiate multiple objects of the view components? For instance instantiate for every available model an own JTable, JPanel, JScrollPane object?
  • change dynamically by listening to change events on the tabbed pane the reference of the underyling model

Solution

  • If you are going to have multiple tabs with a different tab having a different model then the answer is easy, you need different tables. At least one for each tab.

    Again, if you multiple tabs then you will also need multiple JScrollPanes, etc.

    However, if you are going to have a single spot for a table, you might be able to get away with a single JTable and multiple models if you aren't doing something custom to the table. (See mKorbel's comment). Either way you could reuse the same JScrollPane.