Java Reference
In-Depth Information
public void mouseReleased(MouseEvent e) {
// Code to handle the mouse button being release...
}
private Point start; // Stores cursor position on press
private Point last; // Stores cursor position on drag
private Element tempElement; // Stores a temporary element
}
private Sketcher theApp; // The application object
}
Directory "Sketcher 4 drawing sketch line and rectangle elements"
You have implemented the three methods that you need to create an element.
The mousePressed() method will store the position of the cursor in the start member of the
MouseHandler class, so this point is available to the mouseDragged() method that is called repeatedly when
you drag the mouse cursor with the button pressed.
The mouseDragged() method creates an element using the current cursor position together with the pos-
ition previously saved in start . It stores a reference to the element in the tempElement member. The last
member of the MouseHandler class is used to store the cursor position when mouseDragged() is called.
Both start and last are of type Point because this is the type that you get for the cursor position, but
remember that Point is a subclass of Point2D , so you can always cast a Point reference to Point2D when
necessary.
The mouseReleased() method is called when you release the mouse button. This method stores the ele-
ment in the sketch and cleans up where necessary.
An object of type MouseHandler is the listener for mouse events for the view object, so you can put this
in place in the SketcherView constructor. Add the following code at the end of the existing code:
public SketcherView(Sketcher theApp) {
this.theApp = theApp;
MouseHandler handler = new MouseHandler();
// create the mouse listener
addMouseListener(handler);
// Listen for button events
addMouseMotionListener(handler);
// Listen for motion events
}
Directory "Sketcher 4 drawing sketch line and rectangle elements"
You call the addMouseListener() and addMotionListener() methods and pass the same listener
object as the argument to both because the MouseHandler class deals with both types of event. Both
methods are inherited in the SketcherView class from the Component class, which also defines an ad-
dMouseWheelListener() method for when you want to handle mouse wheel events.
Let's go for the detail of the MouseHandler class now, starting with the mousePressed() method.
Handling Mouse Button Press Events
Search WWH ::




Custom Search