当 JCheckBox 由表模型生成时初始化它们
在 Java Swing 中,我创建了一个 JTable
,它使用扩展 DefaultTableModel
的表模型类。由于表中一行的值是布尔类型,因此这些值显示为复选框。由于我想向这些复选框添加“项目侦听器”类,因此我确实需要初始化每个复选框。但是如果这些是表模型自动创建的怎么办?
In Java Swing I have created a JTable
which uses a table model class which extends DefaultTableModel
. As the values of one row of the table are of boolean type, these are displayed as check-boxes. As I want to add to these check-boxes 'item listeners' classes, I do need to initialize each of these check-boxes. But how do I do if these are automatically created by the table model?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于这些复选框更改了基础数据,因此添加
TableModelListener
并对该列的tableChanged
事件做出反应。As these CheckBoxes change the underlying data, it should be sufficient to add a
TableModelListener
and react totableChanged
events of that column.简而言之,您无法将 ActionListener 添加到表中的 JCheckbox,原因有两个:
我认为重要的是要问为什么您需要这些活动?您给出的答案将反映应采取的最佳方法。
如果您希望允许用户编辑复选框的状态,最好的方法可能是重写
TableModel.isCellEditable(int, int)
为复选框列返回 true,然后简单地更新原始数据当 TableModel 更新时。The short answer is you can't add ActionListeners to the JCheckboxes in the table for two reasons:
I think it's important to ask why you need these events? The answer you give will reflect the best approach to take.
If you want to allow the user to edit the state of the checkboxes, your best approach may be to override
TableModel.isCellEditable(int, int)
to return true for the Checkbox columns and then simply update original data as the TableModel is updated.