Home Java Java-tips GUI Components 80combo_box JComboBox - Tutorial on JComBoBox

Ask Questions?

View Latest Questions

Advertisement


 
 

JComboBox - Tutorial on JComBoBox
Posted on: July 22, 2006 at 12:00 AM
There are several ways to select one of many fixed choices.

Java: JComboBox (uneditable)

Making Choices

There are several ways to select one of many fixed choices: radio buttons, a menu, a list, or a (uneditable) combo box. A combo box (JComboBox) is a popup menu and is often the best component to use because it uses less space than radio buttons or a list, and it shows as part of a "form" so the user realizes it's there, unlike a menu.

You can also use an editable combo box, and in this case the user can either choose from the pop-up menu or type in a value.

Constructor

An easy way to build a combo box is to initialize an array (or Vector, but not yet the new Collections types) of strings and pass it to the constructor. Objects other than strings can be used, but this is the most common. The list also be built by successive calls to the add method.
String[] dias = {"lunes", "martes", "miercoles"};
JComboBox dayChoice = new JComboBox(dias)

Common methods

In these prototypes, assume the following.
   int index;
   String item;
   String obj;  // obj can be any object type, but is commonly String
   JComboBox cb = new JComboBox(. . .);
ResultCallDescription
cb.addActionListener(...);Add listener -- same as for button.
Modifying a JComboBox
cb.setSelectedIndex(index);Set default, visible, choice.
cb.setSelectedItem(obj);Set default, visible, choice.
cb.add(item);Add additional item to the list
cb.insert(item, index);Add additional item after index.
cb.remove(item);Remove item from the list
cb.remove(index);Remove item as position index
Testing a JComboBox
index =cb.getSelectedIndex();Return index of selected item.
obj =cb.getSelectedItem();Return selected item.

Events

A JComboBox generates both ActionEvents (like buttons, text fields, etc), or ItemEvents. Because it is easier to work with ActionEvents, we'll ignore the ItemEvents. When the user chooses an item from a combo box, an ActionEvent is generated, and the listener's actionPerformed method is called. Use either getSelectedIndex to get the integer index of the item that was selected, or getSelectedItem to get the value (eg, a String) that was selected.

Example

This example creates a JComboBox, and adds a listener to it. The getSelectedItem method returns an Object type, so it's necessary to downcast it back to a String.
String[] fnt = {"Serif", "SansSerif", "Monospaced"};
JComboBox fontChoice = new JComboBox(fnt);

fontChoice.addActionListener(
    new ActionListener() {
        public void actionPerformed(ActionEvent e) {    
            JComboBox combo = (JComboBox)e.getSource();
            currentFont = (String)combo.getSelectedItem();
        }
    }
);
Copyleft 2003 Fred Swartz MIT License, Last update: 2003-10-30
Advertisement


DMCA.com