Combo box In Java

In this section, you will learn about the JComboBox Component of swing in java.

Combo box In Java

This tutorial will help you to create a Combo box in java. Combo box allow you to select one of the option which appear at the user request. It is possible that combo box can be editable by which a user can type a value in the editable field. Combo box can be created using JCombobox in java which  is sub classed to JComponent. It provides you options to select an item from the item list. You can never select more than one item from a combo box. Combo Box can be either editable or  non-editable means only readable.

Constructor of JCombobox are as follows:

  • JComboBox() : Create a combo box with a default.
  • JCombobox(ComboBoxModel a) : Create a combo box that accept item from the existing combo box mode.
  • JComboBox(Object[]  ob) : Create a combo box that contain the element in the array.
  • JComboBox(Vector <?>  v) : Create a vector that contain the element in vector.

And, some of the method of JComboBox are actionPerformed(ActionEvent e) which is implemented as public,  addItem(Object a) which add an item to the item list, addItemListener(ItemListener listener) which adds an ItemListener, getAction() which returns the currently set action for this ActionEvent Source, getActionCommand() which return the action command included in the event. Now, with the help of the example we are going to create.

Example : Combo Box in Java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Combobox {
	JComboBox combo;
	JTextField txt;

	public static void main(String[] args) {
		Combobox b = new Combobox();

	public Combobox() {
		String country[] = { "India", "Australia", "Canada", "Boston" };
		JFrame frame = new JFrame("JComboBox Example");
		JPanel panel = new JPanel();
		combo = new JComboBox(country);
		txt = new JTextField(10);
		frame.setSize(300, 300);
		combo.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent ie) {
				String str = (String) combo.getSelectedItem();


Output from the program:

Download Source Code