Combo Boxes (JComboBox)

It's quite often that users will need to pick from a number of pre-determined options, so rather than providing the oportunity for them to type text, to avoid potential mistakes, we can provide them with a list (frequently known as a 'drop-down list'). The Swing UI provide the means to do this with a control called JComboBox (shown below)

A JComboBox

Assuming you have a pre-existing Swing JPanel with a bound class set up, drag a JComboBox from the toolbox onto the JPanel.

Once you've added the box, select it in the editor and set its field name property to titleComboBox, or an appropriate name of your choosing. Next check the custom create box. Clicking this box will add the code below to the associated class (if it does not exist already):

private void createUIComponents() {
    // TODO: place custom component creation code here
}

The text displayed as options in the comboBox will be the result of calling toString() on whatever type(s) of object are added to the comboBox. This example will use Strings as the objects (so the text displayed will be the text of the String)

Modify the code in the createUIComponents() method so it initialises the JComboBox and adds a series of professional titles to the comboBox as follows:

private void createUIComponents() {

    titleComboBox = new JComboBox();
    titleComboBox.addItem("Dr");
    titleComboBox.addItem("Miss");
    titleComboBox.addItem("Mr");
    titleComboBox.addItem("Mrs");
    titleComboBox.addItem("Ms");
    titleComboBox.addItem("Prof");
    titleComboBox.addItem("Rev");
}
Note that if we already had a collection of objects, we could iterate through it to add them, rather than adding them one by one

If you run the form, you should now be able to see a list of options.

Accessing the selected item

Instances of JComboBox have an method called getSelectedItem() because the items can be any form of object, this method will return an Object. As we know what type of objects we added to the JComboBox, we can 'cast' the object to that type (in this case String). To cast an object of one type as a (known) subtype, we simply prefix the object with the type in brackets, in this case, to cast it as a String we would write the following code:

String selectedItem = (String)titleComboBox.getSelectedItem();
If we were to omit the (String) code, the IDE would show an 'Incompatible Types' error.

Executing code on change of selection

It is possible to can execute code if a user makes or changes a selection. JComboBox allows you to add an event listener (just like JButton), and it is created in the same way.

Task

Further task

Another control, JList can display a series of data based on a Collection of objects. Rather than adding one object at a time however, it can be assigned the entire collection