Method complementDisk complements the disk-present property —if there
is a disk, it removes the disk, and vice versa. Method clearDisk makes sure
there is no disk. Both methods call repaint , telling the system that the square
must be repainted.
Registering for mouse clicks
Now look in Fig. 17.16 at class MouseEvents , which is defined at the bot-
tom of class Square . You may not have known that one class can be declared
within another. Class MouseEvents is an inner class of class Square . We need
it to be an inner class so that, by the inside-out rule (see Sec. 2.4), its method
mouseClicked can reference method complementDisk .
A complete understanding of inner classes is given in Sec. 12.4. But you do
not need that complete understanding to continue here.
Class MouseEvents extends class MouseInputAdapter and overrides its
method mouseClicked . This method is to be called when there is a mouse click
on the component. Here, the method simply calls complementDisk , so if there
was a disk, there will not be, and vice versa.
An instance of class MouseEvents has to be registered as a listener for the
Square . This is done in the constructor of class Square using this statement:
this .addMouseListener( new MouseEvents());
That is all there is to listening to a mouse click: Write a (inner) class that has
the method that responds to a mouse click and register an instance of the class as
About class MouseInputAdaptor
Class MouseInputAdaptor has six methods for dealing with mouse events:
1. when the mouse enters the component.
2. when the mouse leaves the component.
3. when the mouse is pressed on the component.
4. when the mouse is released on the component.
5. when the mouse is clicked on the component.
6. when the mouse is dragged beginning in the component.
These methods do not do anything unless you override them. For most simple
GUI applications, mouseClicked is the only method you need to define.
Mouse events: class MouseDemo
The GUI window (in all three states) of Fig. 17.15 is an instance of class
MouseDemo of Fig. 17.17. It makes use of class Square . We discuss MouseDemo .
Three fields, leftColumn , b00, and b01 , are initialized with values that
make up the two lefthand boxes of the GUI. Similarly, fields rightColumn , b10 ,
and b11 make up the two righthand boxes. There are two other fields: Button jb