JComboBox (un-editable form)


Summary:

The GUI element described in this tutorial is the JComboBox.  There are two very different types of combo boxes; the more common, default version, is the un-editable combo box, as apposed to the editable form.  This document will focus on the former, un-editable version.

The combo box, also known as a “drop down” menu is a very common element in user interfaces.  It allows the user to select one of many options contained within a small, (sometimes scrolling) pane without having to move around the entire screen to make a choice.  By holding many options, but only displaying one when not in use, drop down menus take up very little screen real estate.  Drop down menus also have one very notable feature in that action events can be applied to option changes.  For example if a user is filling out an address form and selects their country as Canada from a dropdown, another dropdown could be triggered to populate with Canadian provinces, as apposed to USA states.

Where to Find It:

The JComboBox can be found in the javax.swing library:
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComboBox.html

The Basics:

Below is a very simple example of how to create and receive input from a JComboBox.  The example creates a JComboBox with 5 musical choices for the user to choose from.  When a choice has been selected, a text field is updated and displays the user’s decision.  The GUI components are set up in the constructor.  After the container, dubbed ‘wholeWindow’, has been created to hold all the components, an array of musical choices is created.  Next, a JComboBox is created that accepts the musical choices array we created.

To show the functionality of adding items once the JComboBox has been created, the next line shows the addItem method being called on the music ComboBox already created.  ComboBoxes also have many remove methods to either remove a specific object such as the string “Jazz” in our example, or to remove an object at a certain index.

After filling the ComboBox, the next step is to add an action listener to it so that we can be notified if a new option has been chosen.  There are many ways to create an action listener, but in this example the inner class method has been chosen.  First, an inner class is created that implements ActionListener.  Then the addActionListener method is called on the ComboBox with a reference to an instance of the action listener as an argument. 

Now, whenever an option from the music list is selected, the actionPerformed method in the ChangeMusicAction class will be called.  A reference to the ComboBox can be extracted from the ActionEvent passed to the method, as seen in the example. Then the getSelectedItem method can be called to get the option the user selected.  Any of your application logic can be coded here, but generally these listeners are used to just receive the information and then delegate the actual work to other methods.

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

 

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.JTextField;

 

public class ComboBoxDemo {

           

/**

* an inner class to exit the program if the window is closed

*/

            private class WindowExitListener extends WindowAdapter {

                        public void windowClosing( WindowEvent e ) {

System.exit ( 0 );

                        }

            }

           

/**

            * an inner class to listen to the combo box

            */

private class ChangeMusicAction implements ActionListener {

                        public void actionPerformed(ActionEvent e) {

                                    JComboBox comboBox = (JComboBox) e.getSource();

                                    String musicChoice = (String) comboBox.getSelectedItem();

                                    updateTextField(musicChoice);

                        }

            }

   

 

            private JTextField textResult;

 

            public ComboBoxDemo() {

                        JFrame window = new JFrame();

               

 //set main gui stuff

                        window.setLocation(100,100);

                        window.setResizable(false);

               

                        //add the window exit listener

                        window.addWindowListener(new WindowExitListener());

               

                        //create a container for the window

                        Container wholeWindow = window.getContentPane();

                        wholeWindow.setLayout( new BorderLayout() );

                       

                        //create an array of music choices used for the example

                        String[] musicChoices = { "Rock", "Jazz", "Country", "Electronica"};

 

                        //create the JComboBox from the music choices created above

                        JComboBox musicList = new JComboBox(musicChoices);

                       

                        //for example reasons: show use of add method:

                        musicList.addItem("Classical");

                       

                        //create a text field that will show the result of the

                        //choice we have chosen from the combo box

                        textResult = new JTextField();

                       

                        //set the selected index

                        musicList.setSelectedIndex(0);

                       

                        //add the action listener that will be called when a different choice has been selected

                        musicList.addActionListener(new ChangeMusicAction());

 

                        //simulate a change of music choice so that the text field will be updated appropriately

                        updateTextField( (String) musicList.getSelectedItem() );

 

                        //Build and show the whole thing

                        wholeWindow.add( musicList, BorderLayout.NORTH );

                        wholeWindow.add( textResult, BorderLayout.SOUTH );

                        window.pack();

                        window.show();

            }

           

            private void updateTextField(String name) {

                textResult.setText(name);

            }

 

            public static void main(String[] args) {

                new ComboBoxDemo();

            }

}

 

Customization:

ComboBoxes can be customized to show other objects instead of just strings, but a custom renderer must be created.  This is outside the scope of this document, but information about creating a custom renderer and a tutorial can be found on Sun’s website.
http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html#renderer

Best Practices:

There are many instances in which combo boxes can be used appropriately in a user interface.  Combo Boxes should be used when space is tight.  Lists of radio buttons are more often easier for a user to manipulate and understand, but if the interface presents the user with a lot of information and options, drop down menus are a good choice.  Another attraction to using drop down menus is that developer can specify only valid inputs so that no validation of data needs to be done.

Limitations:

ComboBoxes present the user with a limited number of options.  If the user doesn’t find an option that fits his/her need, they may become confused.  ComboBoxes are ideal for when the user has a few options to choose from.  As the number of elements rises, the usability generally goes down. For a large number of elements, it can be difficult for the user to scroll through every value until finding the one they need.  Also, ComboBoxes only allow the user to select one option while other list choices such as checkboxes can allow multiple selections.

Things to Watch Out for When Including JComboBoxes:

JComboBoxes are very easy to implement and there isn’t much for the developer to stumble on.  Problems can arise when developers start to extend and customize the JComboBox such as adding objects other than strings to the ComboBox.  The creation of custom renderers is required and they can be slightly complicated to understand

References:

Other Helpful Resources: