问题
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
回答1:
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.
回答2:
If the structure of the table stays the same (i.e. same number of columns, same titles, same column classes), and only its content changes, you should keep the same model instance but change the data (and call fireTableDataChanged
).
This will be more efficient, and will allow keeping the current column order, the current sorted column, etc.
If the structure of the table completely changes, changing the model itself is probably easier. You could also call fireTableStructureChanged
, but the javadoc of this method says :
This is the same as calling setModel(TableModel) on the JTable
Regarding the tabs, the same rule can be followed.
来源:https://stackoverflow.com/questions/6520773/multiple-instances-of-model-components-in-java-swing