Java Reference
In-Depth Information
LISTING 5.13
continued
//*****************************************************************
// Represents a listener for both buttons.
//*****************************************************************
private class
ButtonListener
implements
ActionListener
{
//--------------------------------------------------------------
// Determines which button was pressed and sets the label
// text accordingly.
//--------------------------------------------------------------
public void
actionPerformed (ActionEvent event)
{
if
(event.getSource() == left)
label.setText("Left");
else
label.setText("Right");
}
}
}
We could have created two separate listener classes, one to listen to the left but-
ton and another to listen to the right. In that case, the
actionPerformed
method
would not have to determine the source of the event. Whether to have multiple
listeners or determine the event source when it occurs is a design decision that
should be made depending on the situation.
Note that the two buttons are put on the same panel called
buttonPanel
,
which is separate from the panel represented by the
LeftRightPanel
class. By
putting both buttons on one panel, we can guarantee their visual relationship to
each other even when the frame is resized in various ways. For buttons labeled
Left and Right, that may be important.
A push button, as defined by the
JButton
class, is only one kind of button that
we can use in a Java GUI. Two other kinds are check boxes and radio buttons.
Let's look at these in detail.
A
check box
is a button that can be toggled on or off using the mouse, indicat-
ing that a particular boolean condition is set or unset. For example, a check box
Search WWH ::
Custom Search