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?
Try to set the cell renderer as well.
Yes, use a JComboBox to render your cells:
You will need to define your own renderer for displaying components on your table, since CellEditors are only needed for editing the value within a tablecell (which is why it only reacts, when you click on a cell).
Maybe have a look at Java Tutorials to learn more about the concept of renderers and editors for JTables.