I'm making a program in JavaGUI where I'm going to get some information from the database and in JTable I can change the values and update the database. But in one of the columns of the database I want a combobox to appear with all the options that the user can choose. When running the program, the query appears and I can edit it, but in the column I want the combobox nothing appears
PreparedStatement pst = con.prepareStatement(m);
rp = pst.executeQuery();
DefaultTableCellRenderer direita = new DefaultTableCellRenderer();
JComboBox<String> comboBox = new JComboBox<>();
comboBox.addItem("Asia");
comboBox.addItem("Europe");
comboBox.addItem("North America");
comboBox.addItem("South America");
comboBox.addItem("Africa");
comboBox.addItem("Antartica");
comboBox.addItem("Australia");
TableColumn testColumn = table.getColumnModel().getColumn(2);
testColumn.setCellEditor(new DefaultCellEditor(comboBox));
direita.setHorizontalAlignment(SwingConstants.RIGHT);
table.setModel(DbUtils.resultSetToTableModel(rp));
table.getColumnModel().getColumn(2).setCellRenderer((TableCellRenderer) comboBox);
CodePudding user response:
TableColumn testColumn = table.getColumnModel().getColumn(2);
testColumn.setCellEditor(new DefaultCellEditor(comboBox));
table.setModel(DbUtils.resultSetToTableModel(rp));
When the model is reset a new TableColumnModel
is created so you lose the customization of the editors and renderers.
The editor needs to be set AFTER the model is set:
table.setModel(DbUtils.resultSetToTableModel(rp));
TableColumn testColumn = table.getColumnModel().getColumn(2);
testColumn.setCellEditor(new DefaultCellEditor(comboBox));
Your renderer is being set correctly.