Question

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 line there should be a Checkbox on the right side, so that the user only can answer with yes or no.

Is this possible to do with an JTable, and how can I achieve this?

regards

Was it helpful?

Solution

You have stated in a comment:

I tried it with a column of JCheckboxes it works but I just want it in one cell

Note this requirement is a little tricky. I think you can override getCellRenderer(int row, int column) and getCellEditor(int row, int column) methods asking for the cell value's class.

This way the cell renderer/editor will be a JCheckbox even when the table's rows are sorted or table's columns are rearranged.

Something like this:

    JTable table = new JTable(model) {
        @Override
        public TableCellRenderer getCellRenderer(int row, int column) {
            if(getValueAt(row, column) instanceof Boolean) {
                return super.getDefaultRenderer(Boolean.class);
            } else {
                return super.getCellRenderer(row, column);
            }
        }

        @Override
        public TableCellEditor getCellEditor(int row, int column) {
            if(getValueAt(row, column) instanceof Boolean) {
                return super.getDefaultEditor(Boolean.class);
            } else {
                return super.getCellEditor(row, column);
            }
        }
    };

Example

Here a complete example to play with.

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

public class Demo {

    private void createAndShowGUI() { 

        DefaultTableModel model = new DefaultTableModel(new Object[]{"Column # 1", "Column # 2"}, 0);
        model.addRow(new Object[]{"Property # 1", "Value # 1"});
        model.addRow(new Object[]{"Property # 2", Boolean.TRUE});
        model.addRow(new Object[]{"Property # 3", "Value # 3"});

        JTable table = new JTable(model) {
            @Override
            public TableCellRenderer getCellRenderer(int row, int column) {
                if(getValueAt(row, column) instanceof Boolean) {
                    return super.getDefaultRenderer(Boolean.class);
                } else {
                    return super.getCellRenderer(row, column);
                }
            }

            @Override
            public TableCellEditor getCellEditor(int row, int column) {
                if(getValueAt(row, column) instanceof Boolean) {
                    return super.getDefaultEditor(Boolean.class);
                } else {
                    return super.getCellEditor(row, column);
                }
            }
        };
        table.setAutoCreateRowSorter(true);

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(new JScrollPane(table));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {                
                new Demo().createAndShowGUI();
            }
        });
    }    
}

Screenshots

enter image description here

OTHER TIPS

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top