Add Combo Box to JTable in Java



In this article, we will learn how to add a JComboBox to a JTable in Java Swing. The JComboBox allows you to create a drop-down list within a table cell, enabling users to select from predefined options.

Steps to add a combo box to JTable

Following are the steps to add a combo box to JTable ?

  • First import the necessary packages.
  • Initialize a JTable with 5 rows and 5 columns.
  • Create a JComboBox and add items to it.
  • Get the first column of the table and set its cell editor to the JComboBox.
  • Add the table to a JFrame.
  • Print the table

Java program to add ComboBox to JTable

The following is an example to add ComboBox 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);
   }
}

Output

The output is as follows displaying JComboBox in JTable -

Code Explanation

In the given code, we will start with importing the classes here the javax.swing package provides the necessary classes. First, a JTable is created with 5 rows and 5 columns. A JComboBox is then instantiated and populated with continent names using the addItem() method. The TableColumn class, from javax.swing.table, is used to get the first column of the table through table.getColumnModel().getColumn(0).

Then we will call the setCellEditor() method of TableColumn with a DefaultCellEditor initialized with the JComboBox. This setup makes the first column cells display a drop-down list. Finally, the table is added to a JFrame, which is then displayed. 

Updated on: 2024-08-19T18:30:53+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements