开发者

JCheckBox Behavior in JTable

开发者 https://www.devze.com 2023-04-04 12:42 出处:网络
I followed the directions somewhere online to insert checkboxes in a JTable. Here is my code to do so:

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.setSele开发者_如何学JAVActed((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:

JCheckBox Behavior in 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? 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. 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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号