Using a JComboBox in a Cell in a JTable Component

If the possible values allowed in a column must be one from a small fixed set of values, a combobox might be appropriate as the cell editor for that column. By using a combobox, it is impossible for the user to input an invalid value.
JTable table = new JTable(); DefaultTableModel model = (DefaultTableModel)table.getModel(); // Add some columns model.addColumn("A", new Object[]{"item1"}); model.addColumn("B", new Object[]{"item2"}); // These are the combobox values String[] values = new String[]{"item1", "item2", "item3"}; // Set the combobox editor on the 1st visible column int vColIndex = 0; TableColumn col = table.getColumnModel().getColumn(vColIndex); col.setCellEditor(new MyComboBoxEditor(values)); // If the cell should appear like a combobox in its // non-editing state, also set the combobox renderer col.setCellRenderer(new MyComboBoxRenderer(values)); public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer { public MyComboBoxRenderer(String[] items) { super(items); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { setForeground(table.getSelectionForeground()); super.setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); } // Select the current value setSelectedItem(value); return this; } } public class MyComboBoxEditor extends DefaultCellEditor { public MyComboBoxEditor(String[] items) { super(new JComboBox(items)); } }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.