Java Reference
In-Depth Information
I want to make a comment about the ItemEvent generated from a combo
box, and how it applies to both Choice and JComboBox components.
When an item is selected, it has been my experience that two item events
occur. (The documentation states that one or two item events may occur,
but it is not clear when you get one and when you get two.) You often
need to make sure you aren't handling the same event twice when
working with a Choice. When using a JComboBox, you can take advantage
of the ActionEvent that occurs when a user selects an item in the combo
box, and not handle the ItemEvent. (See the SelectionDialog program in
this chapter for an example of handling the ActionEvent of a JComboBox.)
Swing Combo Boxes
A Swing combo box is different from an AWT one in that a JComboBox can be
made editable, allowing the user to add items to the combo box. Also, a JCom-
boBox generates both an ItemEvent and an ActionEvent when the user makes
a selection. A JComboBox also generates a PopupMenuEvent when the user
clicks the arrow to display the contents of the combo box.
The JComboBox class has four constructors:
public JComboBox(). Creates a new, empty combo box.
public JComboBox (Object [] items). Creates a combo box with the
given array of objects as its initial data.
public JComboBox (Vector items). Creates a combo box with the ele-
ments of the Vector as its initial data.
public JComboBox (ComboBoxModel items). Creates a combo box with
the given ComboBoxModel. A ComboBoxModel object uses a Vector to
maintain the elements of the combo box.
The following code from the SelectionDialog program available on the Web
site for this topic demonstrates using JComboBox, as well as a JList. Study the
program and try to determine how the GUI looks.
String [] comboBoxItems = {“Right”, “Left”};
direction = new JComboBox(comboBoxItems);
String [] listItems = {“Sunday”, “Monday”, “Tuesday”, “Wednesday”,
“Thursday”, “Friday”, “Saturday”};
left = new JList(listItems);
right = new JList();
left.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
right.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Search WWH ::




Custom Search