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:

JComboBox