Checkbox in only one JTable Cell

前端 未结 2 953
臣服心动
臣服心动 2021-01-28 04:40

I want to create an JTable with 2 columns, which looks like a survey. So on the left are the questions and on the right the user can give his answers. But in one li

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-28 05:13

    You can implement the interface TableCellRenderer to create a custom renderer for cells that have different objects, like a JTextField and JLabel. You must implement the method getTableCellRendererComponent and from it you can return a component (like a JPanel or what you wish) with the components that you wish to show on the cell. In the table, you will use JTable.setDefaultRenderer() to set your new renderer for a custom class.

    If you have only 2 values, maybe you can also set your data to boolean values and let the table display it as a CheckBox (default rendering).

    This is the code for the second method, which seems to be more like what you want.

    class CheckBoxModel extends AbstractTableModel{
    
            private final Object[][] rowData = {{"John" , true}, {"Mary", false}};
            final String columnNames[] = { "Student", "Approve" };
    
            @Override
            public int getRowCount() {
                return rowData.length;
            }
    
            @Override
            public int getColumnCount() {
                return columnNames.length;
            }
    
            @Override
            public Class getColumnClass(final int columnIndex) {
                if (columnIndex == 1) {
                    return Boolean.class; //renders column as a CheckBox
                }
                return super.getColumnClass(columnIndex);
            }
    
            @Override
            public Object getValueAt(final int rowIndex, final int columnIndex) {
                return rowData[rowIndex][columnIndex];
            }
    
            @Override
            public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) {
                rowData[rowIndex][columnIndex] = aValue;
                fireTableCellUpdated(rowIndex, columnIndex);
            }
    
            @Override
            public boolean isCellEditable(final int rowIndex, final int columnIndex) {
                return true;    //makes all cells editable
            }
    }
    

    And a test class:

    public class TestTable {
    
        public static void main(String[] args) {
            final JFrame frame = new JFrame("Editable Color Table");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final JTable table = new JTable(new CheckBoxModel());
            final JScrollPane scrollPane = new JScrollPane(table);
            frame.add(scrollPane, BorderLayout.CENTER);
            frame.setSize(500, 500);
            frame.setVisible(true);
        }
    }
    

提交回复
热议问题