How to Create Combo Boxes in Java - dummies

By Doug Lowe

In Java, you can create combo boxes. A combo box is a combination of a text field and a drop-down list from which the user can choose a value. If the text-field portion of the control is editable, the user can enter a value in the field or edit a value retrieved from the drop-down list.


You use the JComboBox class to create combo boxes. Creating a combo box is easy. You have three constructors to choose among, the first of which creates an empty combo box:

JComboBox combo1 = new JComboBox();

Then you can use the addItem to add items to the combo box:


Alternatively, you can create a combo box and initialize its contents from an array, as in this example:

String[] theSeven = {"Bashful", "Doc", "Dopey",
      "Grumpy", "Happy", "Sleepy",
JComboBox combo1 = new JComboBox(theSeven);

Or if you have an existing Vector object with the data you want to display, you might use this code:

JComboBox combo1 = new JComboBox(vector1);

If the data you want to display is in an array list or another type of collection, use the toArray method to convert the collection to an array and then pass the array to the JComboBox constructor, like so:

JComboBox combo1 = new JComboBox(arraylist1.toArray());

You can add any kind of object you want to a combo box. The combo box calls the toString method of each item to determine the text to display in the drop-down list. Suppose that you have an array of Employee objects. If you create a combo box from this array, the string returned by each employee’s toString method is displayed in the combo box.

By default, the user isn’t allowed to edit the data in the text field portion of the combo box. If you want to allow the user to edit the text field, call setEditable(true). Then the user can type a value that’s not in the combo box.

To remove items from the combo box, use one of the remove methods. If you know the index position of the item you want to remove, call the removeItemAt method and pass the index number as a parameter. Otherwise, if you have the object you want to remove, call removeItem and pass the object.

To remove all the items in a combo box, call removeAllItems. Suppose that you have a combo box named custCombo that’s filled with Customer objects read from a file, and you need to refresh this combo box periodically to make sure that it has all the current customers. Here’s a method that does that:

private void fillCustomerCombo()
 ArrayList<Customer> customers = getCustomers();
 for (Customer c : customers)

In this example, a method named getCustomers is called to get an ArrayList of customer objects from the file. Then all the items currently in the combo box are deleted, and an enhanced for loop is used to add the customers to the combo box.