简体   繁体   English

JTable中的JCheckBox行为

[英]JCheckBox Behavior in JTable

I followed the directions somewhere online to insert checkboxes in a JTable. 我按照在线某处的指示在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: 我设法将复选框添加到JTable,但是当我运行程序时,我得到以下行为:

在此输入图像描述

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? 当用户点击复选框时,如何允许用户选中复选框,而不是从下拉菜单中选择True或False? Thanks! 谢谢!

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. 您所要做的就是在TableModel类中,重写getColumnClass(int index)方法并让它返回需要复选框的列的Boolean.class。 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. JTable将自动使用列的渲染器和编辑器的复选框,以非常简单的方式解决您的问题。 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 关于JTables的Oracle教程将告诉你所有这些以及更多: 如何使用表

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

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