Java Reference
In-Depth Information
EVENT ACTION
Button 1
Pressed
Save the cursor position somewhere as the starting point for the shape. This is the first point on a line, a
corner of a rectangle, or the center of a circle. You store this in a data member of the inner class to Sketch-
erView that you create to define listeners for mouse events.
Mouse
Dragged
Save the current cursor position somewhere as the end point for a shape. This is the end of a line, the opposite
corner of a rectangle, or a point on the circumference of a circle. Erase any previously drawn temporary
shape, and create a new temporary shape from the starting point that was saved initially. Draw the new tem-
porary shape.
Button 1
Released
If there's a reference to a temporary shape stored, add it to the sketch model and redraw it.
The shape that is created is determined by the value stored in the elementType member of the Sketch-
erFrame class. The color of the shape is the color stored in the elementColor member. Both can be changed
by the user at any time using the menu items and toolbar buttons you added in the previous chapter.
Remember from Chapter 18 that there are two mouse listener interfaces: MouseListener , which has
methods for handling events that occur when any of the mouse buttons are pressed or released, and
MouseMotionListener , which has methods for handling events that arise when the mouse is moved. Also
recall that the MouseInputAdapter class implements both, and because you need to implement methods
from both interfaces, you add an inner class to the SketcherView class that extends the MouseInputAd-
apter class.
Because there's quite a lot of code involved in this, you first define the bare bones of the class to handle
mouse events and then continue to add the detail incrementally until it does what you want.
Implementing a Mouse Listener
Add the following class outline as an inner class to SketcherView :
import javax.swing.JComponent;
import java.util.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import javax.swing.event.MouseInputAdapter;
class SketcherView extends JComponent implements Observer {
// Rest of the SketcherView class as before...
class MouseHandler extends MouseInputAdapter {
@Override
public void mousePressed(MouseEvent e) {
// Code to handle mouse button press...
}
@Override
public void mouseDragged(MouseEvent e) {
// Code to handle the mouse being dragged...
}
@Override
Search WWH ::




Custom Search