11 // Add mouse press listener
12
13 class MousePressListener implements MouseListener
14 {
15 public void mousePressed(MouseEvent event)
16 {
17 int x = event.getX();
18 int y = event.getY();
19 component.moveTo(x, y);
20 }
21
22 // Do-nothing methods
23 public void mouseReleased(MouseEvent event) {}
24 public void mouseClicked(MouseEvent event) {}
25 public void mouseEntered(MouseEvent event) {}
26 public void mouseExited(MouseEvent event) {}
27 }
-
Only the mousePressed event is of interest, but all 5 methods of the MouseListener interface must be implemented. So empty implementations are given for the other 4.
-
The MousePressListener class is used to provide a controller for the RectangleComponent. So it needs a way of referencing the component. See line 19.
-
The mousePressed method can reference component in this case because:
- MousePressedListener is an inner class defined in method main
- component is a final local variable also defined in main.
Note: Inner classes defined in a method can only access local variables of the method if they are declared with the final qualifier!
So component is defined in main:
...
7 public static void main(String[] args)
8 {
9 final RectangleComponent component = new RectangleComponent();
...