[an error occurred while processing this directive]

Create a JComboBox Component in Java

                         

In this section, you will learn about the JComboBox Component of swing in java. The JComboBox is used to display drop-down list. It provides you options to select an item from the item list. You can never select more than one items from a combo box. Combo Box can be whether editable or only non-editable means only readable.

This program displays a simple combo box on the frame which contains multiple items like: BCA, MCA, PPC etc. The background color of this combo box is gray and foreground color is red. Here, the background color of the combo box and the foreground color is set using the setBackground(Color) and setForeground(Color) method of the JComboBox class. When you select the item from the combo box then the selected item is displayed in the text box. Image of the result for the given program is as follows in the pictorial form:

Swing Combo Box Component

And
Swing Drop-Down List

APIs used in the program:

JComboBox:
This is the class which is used to create a combo box in swing using it's constructor.

itemStateChanged():
This is the method which receives the ItemEvent generated by the addItemListener() method of the JComboBox class. The event is generated when you select item from the combo box.

Here is the code of program:

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 course[] {"BCA","MCA","PPC","CIC"};
    JFrame frame = new JFrame("Creating a JComboBox Component");
    JPanel panel = new JPanel();
    combo = new JComboBox(course);
    combo.setBackground(Color.gray);
    combo.setForeground(Color.red);
    txt = new JTextField(10);
    panel.add(combo);
    panel.add(txt);
    frame.add(panel);
    combo.addItemListener(new ItemListener(){
      public void itemStateChanged(ItemEvent ie){
        String str = (String)combo.getSelectedItem();
        txt.setText(str);
      }
    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400,400);
    frame.setVisible(true);
  }
}

Download this example.

                         

[an error occurred while processing this directive]