Java JComboBox 图标

Java JComboBox icon

正在 JTable 中显示数据。一列用作字段复选框。问题是显示 ChceckBox 而不是图标出现在 true/false 中。我该如何解决这个问题?

添加数据:

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();

    }

并在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);

模型的 getColumnClass(int columnIndex) 方法应该 return Boolean.class 用于适当的列索引,以便呈现器知道为该列呈现一个复选框。例如,...

DefaultTableModel headermodel = new DefaultTableModel(){

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

您不必为此设置这些列的单元格渲染器,因为默认单元格渲染器会适当地处理 Boolean.class