Java Reference
In-Depth Information
25.
}
26.
else
{
27.
System.out.println("ERROR: Unexpected ActionCommand");
28.
}
29.
//
End of own code
30.
}
31.
}
In the code for the class
CounterListener
we find the word
implements
instead
of
extends
. This is due to the fact that
ActionListener
is an interface and not
a class. The constructor receives a
CounterPanel
as an argument. The listener
then 'knows' which counter panel it has to update. Check Section B.4 for more
details on this.
The heart of class
CounterListener
is the implementation of the method
ac-
tionPerformed
.Wefirst determine which of the two buttons had been pressed.
This is done by inspecting the action event object
evt
that the method
action-
Performed
received from the runtime system. The line
String actionCommand = evt.getActionCommand();
extracts the
action command
out of the event object
evt
. The action command
is usually the text of the button which has been pressed. In our case it can only
be 'Up' or 'Down'. We use an if-then-else structure to check which one it was
2
.
Depending on the outcome of the test we call the method
increment
or
decrement
of the counter panel. At this point we see why the listener is given a reference to a
CounterPanel
in the constructor. The listener thereby knows which panel it has
to update in response to the event.
In the listing of
CounterPanel
the comment signs at Lines 29 to 31 are removed.
These lines are
CounterListener countList =
new
CounterListener(
this
);
upButton.addActionListener(countList);
downButton.addActionListener(countList);
The first one creates an instance of
CounterListener
. The listener receives a
reference (
this
)tothe panel in the constructor. The next two lines associate
the listener to both buttons of the GUI. This completes the implementation of
our GUI. Figure 3.3 shows what the application looks like. The structure of the
its.CounterGUI
package can be found in Figure 3.4 as an UML-like diagram
3
.
2
The last case can only be reached if the action command is neither 'Up' nor 'Down'. We added
this case to make sure that we become aware of an error that could be due, for example, to
changing the text of the buttons in the counter panel.
3
UML stands for 'Unified Modelling Language'. UML is used to specify the structure of object-
oriented programs also by using graphical representations by the class structure. For more
details see the topic by Fowler and Scott in Section 1.5.
Search WWH ::
Custom Search