Java Reference
In-Depth Information
SELF-REVIEW QUESTIONS
SR 5.26
What are the advantages of using an
ArrayList
object?
SR 5.27
What type of elements does an
ArrayList
hold?
SR 5.28
Write a declaration for a variable named
dice
that is an
ArrayList
of
Die
objects.
SR 5.29
What output is produced by the following code fragment?
ArrayList<String> names =
new
ArrayList<String>();
names.add ("Andy");
names.add ("Betty");
names.add (1, "Chet");
names.add (1, "Don");
names.remove (2);
System.out.println (names);
In Chapter 4 we began our exploration of creating programs with a truly interac-
tive graphical user interface (GUI). You'll recall that interactive GUIs require that
we create listener objects and set up the relationship between listeners and the
components that generate the events of interest.
Let's look at an example in which one listener object is used to listen to two
different components. The program represented by the
LeftRight
class, shown
in Listing 5.12 displays a label and two buttons. When the left button is pressed,
the label displays the word Left, and when the right button is pressed, the label
displays the word Right.
The
LeftRightPanel
class, shown in Listing 5.13, creates one instance of the
ButtonListener
object, then adds that listener to both buttons. Therefore, when
either button is pressed, the
actionPerformed
method of the
ButtonListener
class is invoked.
On each invocation, the
actionPerformed
method uses an
if-else
statement
to determine which button generated the event. The
getSource
method is called
on the
ActionEvent
object that the button passes into the
actionPerformed
method. The
getSource
method returns a reference to the component that gener-
ated the event. The condition of the
if
statement compares the event source to
the reference to the left button. If they don't match, then the event must have been
generated by the right button.
Search WWH ::
Custom Search