在 Java 中的 JTable 中添加 JCombobox 时出现问题?

发布于 2024-11-08 02:55:19 字数 895 浏览 7 评论 0原文

我在 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));

一切正常,直到我使用代码动态添加新行到表中:

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();

数据已添加到表中,但不能再选择最后一列中的组合框。当我单击该行时,组合框仍然显示,但无法选择值。 请问我该如何处理这个问题?

I have added a combobox in a JTable, the adding code as follows:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阳光的暖冬 2024-11-15 02:55:20

切勿使用 updateUI() 方法。阅读 API 以了解此方法的实际用途。它与更改模型中的数据无关。

JTable 已经支持组合框编辑器,因此无需创建自定义 MyComboBoxEditor。阅读 JTable API 并点击有关“如何使用表”的 Swing 教程的链接,了解使用组合框作为编辑器的工作示例。

Never use the updateUI() method. Read the API to see what this method actually does. 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. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文