Java Reference
In-Depth Information
and and the horizontal box
b
that contain vertical boxes
leftColumn
and
rightColumn
.
Now look at the constructor of class
MouseDemo
. After the superconstructor
is called, the following happens:
Obtain the class
in Fig. 17.16
from lesson page
17-4.
1. The left column of boxes is created and added to
Box b
.
2. The right column of boxes is created and added to
Box b
.
3. Horizontal box b and button jb are added to the content pane.
4. A button listener is registered with button
jb
(we look at this later).
5. The
JFrame
is packed.
6. The
JFrame
is fixed so that it cannot be resized.
Registering a button listener
Button
jb
, the initialize button, needs a listener. Recall that to handle a click
of a mouse button, a method
actionPerformed
has to be written and an object
that contains this method has to be registered with the button, using the button's
method
addActionListener
.
Class
MouseDemo
has an inner class, which provides method
actionPer-
formed
. This class is written as an inner class so that the method can call meth-
ods
clearDisk
of the four squares to remove any pink disks on them —notice
the four calls in the body of method
actionPerformed
.
Step 4 in the list above registers an instance of this class with button
jb
,
using the statement:
jb.addActionListener(
new
ButtonListener());
This concludes our discussion of class
MouseDemo
. Looked at as a whole, it
can seem quite daunting. But broken down into its constituent pieces, it is quite
logical and reasonable. We urge you to get a copy of these classes from the CD
and experiment with them to see that the clicking of buttons really works.
Listening to the Squares in class MouseDemo
We placed the listener for mouse events on a square in class
Square
. This
was easier because, in the
Square
constructor, we had to register only one mouse
listener (although that registration happens whenever an instance is created).
Registering the mouse listeners in class
MouseDemo
is also possible. It has
the disadvantage that a listener for each
Square
must be registered separately. It
has the advantage that only class
MouseDemo
knows the precise location of each
Square
, and this information may be necessary when processing some mouse
events, like mouse drags and releases. We do not explore this issue further.
17.4.4
Listening to other components
Listening to other components besides buttons and mouse clicks is similar to lis-
tening to buttons. One registers a listener with that component. Therefore, we do
not discuss listening to other components in this paper text.
Search WWH ::
Custom Search