Search code examples
javaswingjtablebooleanjcheckbox

Java JComboBox icon


Displaying data in a JTable. One column serves as a field Checkbox. The problem is that instead of the icon appears in the display ChceckBox true / false. How do I fix this?

Add data:

private DefaultTableModel headermodel = new DefaultTableModel();
private JScrollPane scrollHeader = new JScrollPane();
private JTable headerTable = new JTable();

 public void loadHead(){


        header = model.getHead();

        int ids=0;
        int id=1;

        for(String head: header) {
            headermodel.addRow(new Object[]{id,head});
            headerMap.put(ids,head);
            id++;
            ids++;
            count++;
         }
        header.clear();

    }

and display data in JTable:

    headerTable = new JTable(headermodel);
    headermodel.addColumn("Lp.");
    headermodel.addColumn("Column Name");
    headermodel.addColumn("Constraint");
    headermodel.addColumn("Sum");
    scrollHeader = new JScrollPane(headerTable);

    TableColumnModel tcm = headerTable.getColumnModel();

                tcm.getColumn(2).setCellEditor(new DefaultCellEditor(new JCheckBox()));
                tcm.getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
                tcm.getColumn(3).setCellRenderer(headerTable.getDefaultRenderer(boolean.class));

add(scrollHeader);

enter image description here


Solution

  • The model's getColumnClass(int columnIndex) method should return Boolean.class for the appropriate column index so that the renderer knows to render a check box for that column. For example,...

    DefaultTableModel headermodel = new DefaultTableModel(){
    
        @Override
        public Class<?> getColumnClass(int columnNumber) {
           if (columnNumber == 2 || columnNumber == 3) {
              return Boolean.class;
           } else {
              return super.getColumnClass(columnNumber);
           }
        }
    }
    

    You shouldn't have to set the cell renderer for these columns for this since the default cell renderer will handle Boolean.class appropriately.