简体   繁体   English

在Java中用JTable添加JCombobox的问题?

[英]Problem with adding JCombobox in JTable in Java?

I have added a combobox in a JTable, the adding code as follows: 我在JTable中添加了一个组合框,添加代码如下:

Vector<String> header = new Vector<String>();
Vector data = new Vector();
String[] h = new String[]{"Music", "Movie", "Sport"};
header.add("Code");
header.add("Name");
header.add("Salary");
 header.add("Hobby");
loadData(); // Add some data to the table
DefaultTableModel tblModel;
tblModel = (DefaultTableModel) this.tblEmp.getModel();
tblModel.setDataVector(data, header);

// Adding combobox to the last column
TableColumn hobbyColumn = tblEmp.getColumnModel().getColumn(3);
hobbyColumn.setCellEditor(new MyComboBoxEditor(h));

Things worked fine until I dynamically add a new row to the table using the code: 事情很好,直到我使用代码动态地向表中添加新行:

Vector v = new Vector();
v.add("E333");
v.add("Peter");
v.add(343);
v.add(""); // This last colum is the combobox so I put it as ""

data.add(v);
tblEmp.updateUI();

Data is added to the table but the combobox in the last column cannot be selected anymore. 数据被添加到表中,但不能再选择最后一列中的组合框。 The combobox is still displayed when I click on the row but cannot select a value. 单击行但仍无法选择值时,仍会显示组合框。 How can I handle this problem, please? 请问我该如何处理这个问题?

Never use the updateUI() method. 永远不要使用updateUI()方法。 Read the API to see what this method actually does. 阅读API以了解此方法实际执行的操作。 It has nothing to do with changing the data in a model. 它与更改模型中的数据无关。

JTable already supports a combo box editor so there is no need to create a custom MyComboBoxEditor. JTable已经支持组合框编辑器,因此无需创建自定义MyComboBoxEditor。 Read the JTable API and follow the link to the Swing tutorial on "How to Use Tables", for a working example of using a combo box as an editor. 阅读JTable API并按照“如何使用表”的Swing教程的链接,获取使用组合框作为编辑器的工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM