Java Program to add Combo Box to JTable


Use the JComboBox to add a combo box to a table -

JComboBox<String> comboBox = new JComboBox<>();

Now, add the combo box items -

comboBox.addItem("Asia");
comboBox.addItem("Europe");
comboBox.addItem("North America");
comboBox.addItem("South America");

Now, use the TableColumn and set the column wherein you want to set the above ComboBox items -

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

Set the editor with the combo box -

testColumn.setCellEditor(new DefaultCellEditor(comboBox));
The following is an example to add JComboBox to JTable:
package my;
import java.awt.Color;
import java.awt.Font;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      JTable table = new JTable(5, 5);
      Font font = new Font("Verdana", Font.PLAIN, 12);
      table.setFont(font);
      table.setRowHeight(30);
      table.setBackground(Color.orange);
      table.setForeground(Color.white);
      TableColumn testColumn = table.getColumnModel().getColumn(0);
      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");
      testColumn.setCellEditor(new DefaultCellEditor(comboBox));
      JFrame frame = new JFrame();
      frame.setSize(600, 400);
      frame.add(new JScrollPane(table));
      frame.setVisible(true);
   }
}

The output is as follows displaying JComboBox in JTable -

Output

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements