Part II
Handling events on a combo box
Part II. Part I was published here
The combo box fires an action event when the user selects an item from the combo box's
menu. The following code from LunarPhases registers and implements an action listener on
the combo box:
| Code: |
phaseChoices.addActionListener(this);
...
public void actionPerformed(ActionEvent event) {
if ("comboBoxChanged".equals(event.getActionCommand())) {
// update the icon to display the new phase
phaseIconLabel.setIcon(
images[phaseChoices.getSelectedIndex()]);
}
}
|
This action listener gets the newly selected item from the combo box, uses that item to
compute the name of an image file, and updates a label to display the image.
Multiple images
In the CelsiusConverter program, we saw how to add a single ImageIcon to a button.
The LunarPhases uses eight images. Only one image of the eight is used at a time, so we
have a choice as to whether we load all the images up front or load the images as they are
needed (known as "lazy image loading"). In this example, the images are all loaded up front
when the class is constructed.
| Code: |
final static int NUM_IMAGES = 8;
final static int START_INDEX = 3;
ImageIcon[] images = new ImageIcon[NUM_IMAGES];
...
// Create the widgets to select and display the phases
private void addWidgets() {
// Get the images and put them into an array of
// ImageIcon.
for (int i = 0; i < NUM_IMAGES; i++) {
String imageName = "images/image" + i + ".jpg";
URL iconURL = ClassLoader.getSystemResource(imageName);
ImageIcon icon = new ImageIcon(iconURL);
images[i] = icon;
}
}
|
Note the use of getSystemResource, a method in ClassLoader that searches the
classpath to find the image file names so that we don't have to specify the fully qualified path
name.
Example five: VoteDialog
The main purpose of this example is to illustrate the use of dialogs, but we'll also explain
how to set up radio buttons.
In this program, the user casts a vote by selecting a radio button and clicking the Vote
button. After the button is clicked, a dialog appears with an informational message or a follow up question. You can close the dialog either by clicking a button in the dialog or explicitly by
clicking the close button.
Here's a picture of the VoteDialog application:

Radio buttons
This application has one action listener that listens to clicks on the Vote button. Each
time the action listener receives an event, the application determines which radio button was
selected and displays the appropriate dialog. For each group of radio buttons, you need to
create a ButtonGroup instance and add each radio button to it.
The ButtonGroup takes
care of unselecting the previously selected button when the user selects another button in the
group. You should generally initialise a group of radio buttons so that one is selected. However,
the API doesn't enforce this rule; a group of radio buttons can have no initial selection. Once
the user has made a selection, exactly one button is selected from then on.
Here is the code from VoteDialog.java in which we create the ButtonGroup instance
and add four radio buttons to it. The setActionCommand method associates a specific dialog
with each radio button item. We use the setSelected method to specify the default selected
radio button.
| Code: |
final int numButtons = 4;
JRadioButton[] radioButtons =
new JRadioButton[numButtons];
final ButtonGroup group = new ButtonGroup();
...
final String defaultMessageCommand = "default";
final String yesNoCommand = "yesno";
final String yeahNahCommand = "yeahnah";
final String yncCommand = "ync";
radioButtons[0] = new JRadioButton("<html>Candidate 1:
<font color=red>Sparky the Dog</font></html>");
radioButtons[0].setActionCommand(defaultMessageCommand);
radioButtons[1] = new JRadioButton("<html>Candidate 2:
<font color=green>Shady Sadie</font></html>");
radioButtons[1].setActionCommand(yesNoCommand);
radioButtons[2] = new JRadioButton("<html>Candidate 3:
<font color=blue>R.I.P. McDaniels</font></html>");
radioButtons[2].setActionCommand(yeahNahCommand);
radioButtons[3] = new JRadioButton("<html>Candidate 4:
<font color=maroon>Duke the Java<font size=-2><sup>TM</sup>
</font size> Platform Mascot</font></html>");
radioButtons[3].setActionCommand(yncCommand);
for (int i = 0; i < numButtons; i++) {
group.add(radioButtons[i]);
}
// Select the first button by default.
radioButtons[0].setSelected(true);
|
Note the use of HTML code on the radio buttons.
Dialogs
In our previous examples, our top-level container has always been a JFrame. Several
classes support dialogs -- windows that are more limited than frames. To create simple,
standard dialogs, you use the JOptionPane class. The dialogs that JOptionPane provides
are modal. When a modal dialog is visible, it blocks user input to all other windows in the
program.

The code for simple dialogs can be minimal. For example, the figure above shows an
instructive dialog.
Here is the code that creates and shows that dialog:
| Code: |
JOptionPane.showMessageDialog(frame,
"There's no \"there\" there.");
|
Every dialog is dependent on a frame.
When that frame is destroyed, so are its
dependent dialogs. When the frame is iconified, its dependent dialogs disappear from the
screen. When the frame is deiconified, its dependent dialogs return to the screen. The AWT
automatically provides this behaviour.
JOptionPane features
Using JOptionPane, you can create and customise several kinds of dialogs.
JOptionPane provides support for laying out standard dialogs, providing icons, specifying the
dialog's title and text, and customising the button text. Other features allow you to customise
the components the dialog displays and to specify where the dialog should appear on-screen.
JOptionPane's icon support lets you easily specify which icon the dialog displays. You
can use a custom icon, no icon at all, or any one of four standard JOptionPane icons (question,
information, warning, and error). Each look and feel has its own versions of the four standard
icons. The following figure shows the icons used in the Java look and feel.

Figure 1: Question, information, warning, and error icons provided by JOptionPane (Java look
and feel shown)
Creating and showing simple dialogs
For most simple modal dialogs, you can use either the showMessageDialog or the showOptionDialog method. The showMessageDialog method displays a simple, one-button
dialog. The showOptionDialog method displays a customised dialog -- it can display a
variety of buttons with customised button text and can contain a standard text message or
a collection of components.
showMessageDialog
Displays a modal dialog with one button, which is labeled OK (or the localised
equivalent). You can easily specify the message, icon, and title that the dialog displays. The
following table shows an example of the use of showMessageDialog in VoteDialog.
| An example using showMessageDialog |
 |
//default title and icon JOptionPane.showMessageDialog(frame,
"This candidate is a dog.
" + "Invalid vote."); |
showOptionDialog
Displays a modal dialog with the specified buttons, icons, message, title, and so on. You
can use this method to change the text that appears on the buttons of standard dialogs. You
can also perform many other kinds of customisation. The following table shows an example
that uses showOptionDialog.
| An example using showMessageDialog |
|
//default title and icon
Object[] options =
\{"Yes!",
"No, I'll pass",
"Well, if I must"\};
int n = JOptionPane.showOptionDialog(
frame,
"Duke is a cartoon mascot. \n" +
"Do you still want to cast your vote?",
"A Follow-up Question",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]); |
The arguments to all the showXxxDialog methods and JOptionPane constructors are
standardised, although the number of arguments for each method and constructor varies. The
following list describes each argument.
Component parentComponent
The first argument to each showXxxDialog method is always the parent component,
which must be a frame, a component inside a frame, or null. If you specify a frame, the
dialog will appear over the center of the frame and will depend on that frame. If you specify
a component inside a frame, the dialog will appear over the center of that component and will
depend on that component's frame. If you specify null, the look and feel picks an appropriate
position for the dialog -- generally the center of the screen -- and the dialog doesn't depend
on any visible frame.
The JOptionPane constructors do not include this argument. Instead, you specify the
parent frame when you create the JDialog that contains the JOptionPane, and you use the JDialog setLocationRelativeTo method to set the dialog's position.
Object message
This required argument specifies what the dialog should display in its main area.
Generally you specify a string, which results in the dialog's displaying a label with the specified
text.
String title
This is the title of the dialog.
int optionType
This specifies the set of buttons that appears at the bottom of the dialog.
You
can choose one of the following four standard sets: DEFAULT OPTION, YES NO OPTION,
YES NO CANCEL OPTION,
OK CANCEL OPTION.
int messageType
This argument determines the icon displayed in the dialog.
Choose from one of
the following values: PLAIN MESSAGE (no icon), ERROR MESSAGE, INFORMATION MESSAGE,
WARNING MESSAGE,
QUESTION MESSAGE.
Icon icon
This specifies the custom icon to display in the dialog.
Object[] options
This further specifies the option buttons to appear at the button of the dialog. Generally,
you specify an array of strings for the buttons.
Object initialValue
This specifies the default value to be selected. You can either let the default icon be
used or specify the icon, using the messageType or the icon argument. By default, a dialog
created with showMessageDialog displays the information icon, and a dialog created with showConfirmDialog displays the question icon. To specify that the dialog display a standard
icon or no icon, specify the message type. To specify a custom icon, use the icon argument.
Getting user input from a dialog
As the code snippets in two tables above show, the showMessageDialog and showOptionDialog methods return an integer indicating the user's choice. The values for
this integer are YES OPTION, NO OPTION, CANCEL OPTION, OK OPTION, and CLOSED OPTION. Each option, except for CLOSED OPTION, corresponds to the button the user
clicked. When CLOSED OPTION is returned, it indicates that the user closed the dialog window
explicitly rather than by choosing a button inside the option pane. The following code detects
whether the yes or no button was selected or the dialog was closed and then sets the frame's
label with the appropriate text.
| Code: |
// yes/no dialog
} else if (command == yesNoCommand) {
int n = JOptionPane.showConfirmDialog(
frame, "This candidate is a convicted felon. \n
Do you still want to vote for her?",
"A Follow-up Question",
JOptionPane.YES NO OPTION);
if (n == JOptionPane.YES OPTION) {
setLabel("OK. Keep an eye on your wallet.");
} else if (n == JOptionPane.NO OPTION) {
setLabel("Whew! Good choice.");
} else {
setLabel("It is your civic duty to cast your vote.");
}
...
|
Even if you change the strings that the standard dialog buttons display, the return value
is still one of the predefined integers. For example, a YES NO OPTION dialog always returns
one of the following values: YES OPTION, NO OPTION, or CLOSED OPTION.
14324 bytes more | comments? | | Score: 0
|