Java Reference
In-Depth Information
Because the
ActionListener
can't identify the selected element, it must ask the
JComboBox
that served as the source of the event. To determine the selected element from the
JComboBox
,
use either
getSelectedItem()
or
getSelectedIndex()
. If an index of -1 is returned, then the
currently selected item isn't part of the model. This seemingly impossible situation happens
when the
JComboBox
is editable and the user has entered a value that isn't part of the original
model.
■
Note
The text string
comboBoxChanged
is the action command for the
ActionEvent
sent to the
ActionListener
when an item within a
JComboBox
changes.
Listening to JComboBox Events with an ItemListener
If you use an
ItemListener
to find out when the selected item within a
JComboBox
changes,
you'll also learn which item was deselected.
To demonstrate both the
ActionListener
and the
ItemListener
, the program shown in
Listing 13-12 attaches both of them to the same
JComboBox
. The
ActionListener
prints its
“action command,” as well as the currently selected item. The
ItemListener
prints the affected
item and the state change for it, as well as the currently selected item.
Listing 13-12.
JComboBox Selection Sample
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SelectingComboSample {
static private String selectedString(ItemSelectable is) {
Object selected[] = is.getSelectedObjects();
return ((selected.length == 0) ? "null" : (String)selected[0]);
}
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
String labels[] = {"Chardonnay", "Sauvignon", "Riesling", "Cabernet",
"Zinfandel", "Merlot", "Pinot Noir", "Sauvignon Blanc", "Syrah",
"Gewürztraminer"};
JFrame frame = new JFrame("Selecting JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox comboBox = new JComboBox(labels);
frame.add(comboBox, BorderLayout.SOUTH);