Java how to create jcombobox cell editor for jtable
In Java Swing, you can create a JComboBox
cell editor for a JTable
by implementing the TableCellEditor
interface and using a JComboBox
as the editor component. Here's an example:
import java.awt.Component; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractCellEditor; import javax.swing.JComboBox; import javax.swing.JTable; import javax.swing.table.TableCellEditor; public class ComboBoxEditor extends AbstractCellEditor implements TableCellEditor { private JComboBox<String> comboBox; private List<String> options; public ComboBoxEditor(List<String> options) { this.options = options; comboBox = new JComboBox<>(options.toArray(new String[0])); } @Override public Object getCellEditorValue() { return comboBox.getSelectedItem(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { comboBox.setSelectedItem(value); return comboBox; } }
In this example, we create a custom TableCellEditor
implementation called ComboBoxEditor
that uses a JComboBox
as the editor component. The ComboBoxEditor
constructor takes a List
of options that will be used to populate the JComboBox
.
The getCellEditorValue()
method returns the currently selected item in the JComboBox
. The getTableCellEditorComponent()
method sets the selected item in the JComboBox
to the current value of the cell being edited and returns the JComboBox
component.
To use the ComboBoxEditor
with a JTable
, you would need to set the editor for the appropriate column. Here's an example of how to do this:
import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; public class TableExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { // Create a table with a default table model JTable table = new JTable(new DefaultTableModel(new Object[][]{{"Option 1"}, {"Option 2"}, {"Option 3"}}, new Object[]{"Options"})); // Set the editor for the second column to the ComboBoxEditor table.getColumnModel().getColumn(0).setCellEditor(new ComboBoxEditor(List.of("Option 1", "Option 2", "Option 3"))); // Add the table to a scroll pane and display it in a frame JFrame frame = new JFrame(); frame.add(new JScrollPane(table)); frame.pack(); frame.setVisible(true); }); } }
In this example, we create a JTable
with a default table model and set the editor for the first column to the ComboBoxEditor
we created earlier. When the user clicks on a cell in the first column, a JComboBox
is displayed that allows them to select from the available options. When they select an option and press Enter, the selected option is displayed in the cell.