Creating ComboBox Using JComboBox Class

In this tutorial, we will show you how to use JComboBox class to create combobox widget in Swing application.

ComboBox is a swing widget that displays a drop down list. A ComboBox gives users options that they can select one and only one item at a time. A ComboBox can be editable or read-only. To create a ComboBox, you use JComboBox class.

Here are the most common constructor of JComboBox class:

JComboBox ConstructorsMeaning
public JComboBox ()Creates a JComboBox instance with default data model.
publicJComboBox(ComboBoxModel model)Creates a JComboBox instance with elements from a specified ComboBoxModel instance.
public JComboBox(Object[] arr)Creates a JComboBox instance with elements from a given array.
public JComboBox(Vector<?> vector)Creates a JComboBox instance that displays elements from a given vector.

You can create a JComboBox instance from an array or vector. Most of the time, you will use ComboBoxModel to manipulate ComboBox’s elements.

To set the ComboBox editable you use the method setEditable(). The default editor will be displayed as an input field(JTextField) which accepts user’s input.

Example of creating a ComboBox by using JComboBox class

In this example we will create a very simple combobox which display a list of element.

Here is the screenshot of the demo application:

package jcomboboxdemo; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Main { public static void main(String[] args) { final JFrame frame = new JFrame("JComboBox Demo"); String[] colorList = {"RED", "GREEN", "BLUE", "CYAN", "DARK GRAY", "MAGENTA", "ORANGE", "PINK"}; final JComboBox cbColor = new JComboBox(colorList); cbColor.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(frame, "Color Selected: " + cbColor.getSelectedItem().toString()); } }); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 100); Container cont = frame.getContentPane(); cont.setLayout(new FlowLayout()); cont.add(cbColor); frame.setVisible(true); } }
Code language: JavaScript (javascript)