Java Swing How to - Create TableCellEditor with JComboBox








Question

We would like to know how to create TableCellEditor with JComboBox.

Answer

import java.awt.Component;
/*from  ww w.j  a v  a2s  .  c om*/
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.TableCellRenderer;

public class Main extends JFrame {

  public Main() {
    DefaultTableModel m = new DefaultTableModel(new Object[][] { { "2", 2, 3 },
        { "1", 4, 5 } }, new Object[] { 1, 2, 3 });
    JTable t = new JTable(m);
    t.getColumnModel()
        .getColumn(0)
        .setCellEditor(
            new DefaultCellEditor(new JComboBox(new String[] { "1", "2" })));
    t.getColumnModel().getColumn(0).setCellRenderer(getCellRenderer());
    t.setRowHeight(25);
    getContentPane().add(new JScrollPane(t));
    pack();
  }

  private TableCellRenderer getCellRenderer() {
    return new TableCellRenderer() {
      JComboBox<String> box = new JComboBox<>(new String[] { "1", "2" });
      @Override
      public Component getTableCellRendererComponent(JTable arg0, Object arg1,
          boolean arg2, boolean arg3, int arg4, int arg5) {
        box.setSelectedItem(arg1);
        return box;
      }
    };
  }

  public static void main(String[] args) throws InterruptedException {
    Main ex = new Main();
    ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ex.setVisible(true);
  }
}