结合@Alican Ozgoren、@mKorbel 和这个答案的建议,您可以构建一个用于通过名称Map<String, NamedModel>
快速访问的。TableModel
public TableModel getTable(String name) {
return map.get(name);
}
下面的示例替换了单个 的模型JTable
,而另一个示例显示了多个表。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
/**
* @see https://stackoverflow.com/a/16611982/230513
* @see https://stackoverflow.com/a/10623134/230513
*/
public class Test {
private static final int N = 25;
private DefaultComboBoxModel dcbm = new DefaultComboBoxModel();
private JComboBox combo = new JComboBox(dcbm);
private JTable table = new JTable(1, 1);
private Map<String, NamedModel> map = new HashMap<String, NamedModel>();
public TableModel getTable(String name) {
return map.get(name);
}
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < N; i++) {
String name = "Table " + String.valueOf(i);
NamedModel model = new NamedModel(name);
map.put(name, model);
dcbm.addElement(model);
}
combo.setSelectedIndex(-1);
combo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TableModel model = (TableModel) combo.getSelectedItem();
table.setModel(model);
}
});
f.add(combo, BorderLayout.NORTH);
f.add(table);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static class NamedModel extends DefaultTableModel {
private String name;
public NamedModel(String name) {
super(1, 1);
this.name = name;
}
@Override
public Object getValueAt(int row, int col) {
return name + ", " + row + ", " + col;
}
@Override
public String toString() {
return name;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Test().display();
}
});
}
}