Java Swing How to - Add JComboBox to the JTable








Question

We would like to know how to add JComboBox to the JTable.

Answer

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
//w w  w  . j ava2 s  . c om
public class Main {

  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setSize(450, 250);

    JTable table = new JTable(5, 5);

    TableColumn testColumn = table.getColumnModel().getColumn(0);

    JComboBox<String> comboBox = new JComboBox<>();
    comboBox.addItem("This");
    comboBox.addItem("is");
    comboBox.addItem("a");
    comboBox.addItem("Sample program");
    testColumn.setCellEditor(new DefaultCellEditor(comboBox));

    frame.add(table);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}