Java Reference
In-Depth Information
Now, whenever button
westButton
(say) is clicked by the user, method
actionPerformed
is called to process the click.
This may seem like a lot of work, but there are only three pieces that you
have not seen before: (1) a procedure that processes mouse clicks, (2) the imple-
ments clause, and (3) a call to register this instance as a listener of the button.
Differentiating among buttons
Procedure
actionPerformed
of Fig. 17.14 does the same thing no matter
which of the two buttons is clicked. In some situations, we want different actions
for different buttons. We describe two ways to identify the source of an event:
Activity
17-4.2
1. Within
actionPerformed
, determine the component that caused the
event. Do this using parameter
e
of procedure
actionPerformed
, which
is a description of the event that caused the method to be called. Method
e.getSource
() yields the component on which the event occurred. So,
we can test whether the component is the east button.
if
(e.getSource == eastButton) ...
2. Provide different
actionPerformed
procedures. This requires providing
different classes to contain the different procedures and takes more work.
It can sometimes best be done using an inner class. We do not discuss this
here but leave it to activity 17-4.2 and a footnote on lesson page 17-4.
17.4.2
Mouse events: class Square
The leftmost
JFrame
in Fig. 17.15 contains a GUI, which contains the basics for
constructing a checkerboard. Click on a square, and a pink disk appears in it, as
shown in the middle
JFrame
. Well, it should be pink, and the squares themselves
are in living red and green, if you look at them in activity 17-4.3. Click again on
the same square and pink disk disappears. Do this any number of times, and for
any square. To remove all the pink disks, click button
initialize
.
Each of the four squares is an instance of class
Square
, which extends class
JPanel
as shown in Fig. 17.16. We do not add components to the
JPanel
. We
only draw on it using methods of class
Graphics
. Each square is
50
by
50
pix-
els. Two fields contain the coordinates of the square —used to print on the
square— and field
hasDisk
indicates whether a disk is present on the square.
The constructor saves its two parameters in the fields and sets the preferred
size of the
JPanel
to
WIDTH
and
HEIGHT
. Its last statement is explained later.
Method
paint
is called by the system whenever the square has to be repaint-
ed. First, it sets the pen color to the background color —green or red— and fills
in the square with that color. Second, if a pink disk is to be drawn, it sets the pen
color to pink and draws the disk. Last, it sets the pen color to black, draws the
border, and draws the coordinates on the square. The order in which these actions
are done is important since each item is drawn on top of the previous one.
Activity
17-4.3
Obtain the class
in Fig. 17.15
from lesson
page 17-4.
Search WWH ::
Custom Search