Java Reference
In-Depth Information
LISTING 8.18
continued
//--------------------------------------------------------------
// Provide empty definitions for unused event methods.
//--------------------------------------------------------------
public void mouseClicked (MouseEvent event) {}
public void mouseReleased (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
}
}
The DotsPanel class keeps track of a list of Point objects that represent all of
the locations at which the user has clicked the mouse. A Point class represents
the ( x, y ) coordinates of a given point in two-dimensional space. It provides pub-
lic access to the instance variables x and y for the point. Each time the panel is
painted, all of the points stored in the list are drawn.
The list of Point objects is maintained as an ArrayList object. More precisely,
the type of the pointList object is ArrayList<Point> , specifying that only Point
objects can be stored in that ArrayList . To draw the points, we use a for loop
to iterate over all the points stored in the list.
The listener for the mouse pressed event is defined as a private inner class that
implements the MouseListener interface. The mousePressed method is invoked
by the panel each time the user presses down on the mouse button while it is over
the panel.
A mouse event always occurs at some point in two-dimensional space, and the
object that represents that event keeps track of that location. In a mouse listener,
we can get and use that point whenever we need it. In the Dots program, each
time the mousePressed method is called, the location of the event is obtained
using the getPoint method of the MouseEvent object. That point is stored in the
ArrayList , and the panel is then repainted.
Note that, unlike the listener interfaces that we've used
in previous examples that contain one method each, the
MouseListener interface contains five methods. For this
program, the only event in which we are interested is the
mouse pressed event. Therefore, the only method in which
we have any interest is the mousePressed method. However,
KEY CONCEPT
A listener may have to provide
empty method definitions for
unheeded events to satisfy the
interface.
 
Search WWH ::




Custom Search