gpt4 book ai didi

java - 通过将参数作为组件名称返回 JTable 的函数

转载 作者:行者123 更新时间:2023-12-04 04:57:12 24 4
gpt4 key购买 nike

public JTable getTable(String Component_name)
{
JTable table=new JTable();
//in this function i want to search all the JTables that have been created on runtime!
//and then i want to return one JTable by the name "Component_Name"//

return table;
}

这就是我想要的功能;我想出了一个解决方案,即创建一个具有私有(private) JTable 表和私有(private)字符串名称的新组件类,但在按名称搜索 JTables 时仍然出现问题。

最佳答案

结合@Alican Ozgoren、@mKorbel 和 answer 的建议, 你可以构造一个 Map<String, NamedModel>快速访问 TableModel按名字。

public TableModel getTable(String name) {
return map.get(name);
}

下面的例子替换了单个 JTable的模型, 而另一个 example显示多个表。

Test image
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();
}
});
}
}

关于java - 通过将参数作为组件名称返回 JTable 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16607311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com