JTable 中的 JCheckBox 行为
我按照网上某处的说明在 JTable 中插入复选框。这是我执行此操作的代码:
protected class JTableCellRenderer implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JCheckBox rendererComponent = new JCheckBox();
rendererComponent.setSelected((Boolean) tableModel.getValueAt(row,
column));
return rendererComponent;
}
}
我设法向 JTable 添加复选框,但是当我运行程序时,我得到以下行为:
当用户单击复选框时,如何允许用户选中该复选框而不是从下拉菜单中选择 True 或 False?谢谢!
I followed the directions somewhere online to insert checkboxes in a JTable. Here is my code to do so:
protected class JTableCellRenderer implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JCheckBox rendererComponent = new JCheckBox();
rendererComponent.setSelected((Boolean) tableModel.getValueAt(row,
column));
return rendererComponent;
}
}
I managed to add checkboxes to a JTable, but then when I run my program, I get the following behavior:
How do I allow a user to check the checkbox instead of selecting True or False from the dropdown menu when he or she clicks on the checkbox? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您遵循的方向很糟糕,因为无需摆弄渲染器或编辑器(顺便说一句,您的问题是您更改了渲染器而不更改编辑器)。您所要做的就是在 TableModel 类中重写
getColumnClass(int index)
方法,并让它为需要复选框的列返回 Boolean.class。就是这样。 JTable 将自动使用列渲染器和编辑器的复选框,以非常简单的方式解决您的问题。当然,不言而喻,该列的数据必须是布尔值才能起作用。有关 JTables 的 Oracle 教程将告诉您所有这些以及更多内容:如何使用表
The directions you are following are bad as there's no need to fiddle with renderers or editors (and by the way, your problem is that you changed the renderer without changing the editor). All you have to do is in your TableModel class, override the
getColumnClass(int index)
method and have it return Boolean.class for the column that needs check boxes. That's it. The JTable will automatically use a checkbox both for the column's renderer and editor solving your problem in a very easy way. Of course it should go without saying that the data for that column must be Boolean for this to work.The Oracle tutorial on JTables will tell you all this and more: How to use Tables