Search code examples
javaswingjtablejcomboboxtablecelleditor

JTable with JComboBox as editor - removing current row


I want to implement a JTable that has one column with JComboBox as editor. I want my table to initially have only one row. After setting the value in ComboBox I want my table to be filled with some values depending on selected element of JComboBox. After selecting non empty element I want to add new row to the table. When there are more than one row not empty and someone sets the value of nth combobox to empty, I want to remove the row from the table.

Simple solution doesn't work:

TableColumn column = table.getColumnModel().getColumn(2);
JComboBox comboBox = new JComboBox();
comboBox.addItem("");
comboBox.addItem("1");
comboBox.addItem("2");
comboBox.addItem("3");
comboBox.addItem("4");
comboBox.addItem("5");
comboBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent e) {
        JComboBox combo = (JComboBox)e.getSource();
        if (combo.getSelectedItem() != null) {
            if (combo.getSelectedItem().equals("")) {
                table.getTableModel().removeRow(table.getSelectedRow());
            } else {
                table.getTableModel().addRow(new Object[] {null, null, null, null});
            }
        }
    }
});
column.setCellEditor(new DefaultCellEditor(comboBox));

Solution

  • As recommended by mKorbel, just implement that logic in your TableModel setValueAt(...) method. here is simple example:

    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    
    public class Example extends JFrame {
    
        private JTable table;
    
        public Example(){
            table = getTable();
            add(new JScrollPane(table));
    
            pack();
            setVisible(true);
        }
    
        private JTable getTable() {
            table = new JTable(new DefaultTableModel(3,3){
                @Override
                public void setValueAt(Object aValue, int row, int column) {
                    super.setValueAt(aValue, row, column);
                    if(column == 2){
                        if(aValue.toString().isEmpty()){
                            removeRow(row);
                        } else {
                            addRow(new Object[] {null, null, null});
                        }
                    }
                }
            });
            TableColumn column = table.getColumnModel().getColumn(2);
            JComboBox<String> comboBox = new JComboBox<>(new String[]{"","1","2","3","4","5"});
            column.setCellEditor(new DefaultCellEditor(comboBox));
            return table;
        }
    
        public static void main(String[] values){
            new Example();
        }
    
    }