Java Reference
In-Depth Information
6
import java.awt.event.MouseMotionAdapter;
7
import java.util.ArrayList;
8
import javax.swing.JPanel;
9
10
public class PaintPanel extends JPanel
11
{
12
// list of Point references
13
private final ArrayList<Point> points = new ArrayList<>();
14
15
// set up GUI and register mouse event handler
16
public PaintPanel()
17
{
18
// handle frame mouse motion event
19
addMouseMotionListener(
20
new MouseMotionAdapter()
// anonymous inner class
21
{
22
// store drag coordinates and repaint
23
@Override
24
public void mouseDragged(MouseEvent event)
25
{
26
points.add(
event.getPoint()
repaint(); // repaint JFrame
);
27
28
}
29
}
30
);
31
}
32
33
// draw ovals in a 4-by-4 bounding box at specified locations on window
34
@Override
35
public void paintComponent(Graphics g)
36
{
37
super .paintComponent(g); // clears drawing area
38
39
// draw all points
40
for (Point point : points)
41
g.fillOval(
point.x, point.y
, 4 , 4 );
42
}
43
} // end class PaintPanel
Fig. 12.34 | Adapter class used to implement event handlers. (Part 2 of 2.)
Class PaintPanel (Fig. 12.34) extends JPanel to create the dedicated drawing area.
Class Point (package java.awt ) represents an x-y coordinate. We use objects of this class
to store the coordinates of each mouse drag event. Class Graphics is used to draw. In this
example, we use an ArrayList of Point s (line 13) to store the location at which each mouse
drag event occurs. As you'll see, method paintComponent uses these Point s to draw.
Lines 19-30 register a MouseMotionListener to listen for the PaintPanel 's mouse
motion events. Lines 20-29 create an object of an anonymous inner class that extends the
adapter class MouseMotionAdapter . Recall that MouseMotionAdapter implements Mouse-
MotionListener , so the anonymous inner class object is a MouseMotionListener . The
anonymous inner class inherits default mouseMoved and mouseDragged implementations,
so it already implements all the interface's methods. However, the default implementa-
 
Search WWH ::




Custom Search