Swing JComboBox

In this tutorial you will learn about the Swing JComboBox and its application with practical example.

Swing JComboBox

It’s a component that combines a button or editable field and a drop-down list. In the JComboBox user can select a value from drop-down list. You can also create ComboBox editable for that combo box include an editable fields.

Table Of Contents

//Class Declaration

JComboBox Constructor

Let’s get more understand about JComboBox, Some of important constructor are listed below.

JComboBox() : This constructor construct a new JComboBox with default data model.

JComboBox(ComboBoxModel<E> aModel): This constructor is used to creates a JComboBox which takes its item from an existing ComboBoxModel.

JComboBox(E[] items): This constructor is used to creates a JComboBox in which elements are contains in the specified array.

JComboBox(Vector<?> items): This constructor is used to creates a JComboBox in which elements are contains in the specified Vector.

JComboBox Methods

Some of commonly used methods are listed below. It will help to know more about JComboBox.

void addItem(E item): By the name it is simply saying that it is used to adds an item in the list of Combo Box.

void addActionListener(ActionListener a): This method is used to add an Action Listener.

void addItemListener(ItemListener aListener): This method is used to add an ItemListener.

E getItemAt(int index): This method is used to return the list item at the specified index or can say position.

int getItemCount(): This method is used to get Number of Item in the List of JComboBox.

void insertItemAt(E item, int index): With the help of this method we can insert item in the list at specified index or position.

boolean isEditable(): This method is used to return that JComboBox is editable or not.

void removeAllItems(): This method simply remove all items from list of JComboBox.

void removeItem(Object anObject): This method is used to remove an item from list of JComboBox.

void removeItemAt(int index): This method is used to removes the item at index. It only works when JComboBox uses a mutable data model.

void setSelectedIndex(int index): This method used to select the item at given index.

void setModel(ComboBoxModel<E> aModel): This method is used to sets the data model that the JComboBox uses to obtain the list of items.

Example :-

An simple example to get understand about JComboBox. Hopefully this will work for you.

Output :-

Output of this code will look like below image. You just need to copy this code and paste it in you program.

image001

In this tutorial we have learn about the Swing JComboBox and its application with practical example. I hope you will like this tutorial.