I’m trying to place a JComboBox inside a certain column of a JTable.
I have this code, and it is working:
model = new DefaultTableModel();
JComboBox<String> optionComboCell = new JComboBox<String>();
optionComboCell.addItem("Option 1");
optionComboCell.addItem("Option 2");
optionComboCell.setSelectedIndex(1);
table = new JTable(model);
// Adding here all the columns, removed for clarity
model.addColumn("Options");
TableColumn optionsColumn = table.getColumn("Options");
optionsColumn.setCellEditor(new DefaultCellEditor(optionComboCell));
My problem with this, is that it doesn’t show as JComboBox until a cell in that column is selected.
When the JFrame is loaded, the whole table looks the same, as if all the cells where only text.
When clicked, it shows the combo box’s arrow and options, but again when deselected, it looks like a regular cell.
Any way to get around that?
Yes, use a JComboBox to render your cells: