Java Swing How to - Create JTable with JComboBox as editor and remove current row








Question

We would like to know how to create JTable with JComboBox as editor and remove current row.

Answer

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;
/*from w ww.ja  v  a  2s .  c o  m*/
public class Main {
  public static void main(String[] values) {
    JTable table;
    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));
    JFrame f = new JFrame();
    f.add(new JScrollPane(table));

    f.pack();
    f.setVisible(true);
  }

}