Java Reference
In-Depth Information
Try It Out— Implementing a Mouse Listener
Add the following class outline as an inner class to SketchView :
import javax.swing.JComponent;
import java.util.*; // For Observable, Observer, Iterator
import java.awt.*; // For Graphics, Graphics2D, Point
import java.awt.event.MouseEvent;
import javax.swing.event.MouseInputAdapter;
class SketchView extends JComponent implements Observer {
// Rest of the class as before
class MouseHandler extends MouseInputAdapter {
public void mousePressed(MouseEvent e) {
// Code to handle mouse button press...
}
public void mouseDragged(MouseEvent e) {
// Code to handle the mouse being dragged...
}
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
}
}
We have implemented the three methods that we will need to create an element. The
mousePressed() method will store the position of the cursor in the start member of the
MouseHandler class, so it will be available to the mouseDragged() method that will be called
repeatedly when you drag the mouse cursor with the button pressed. The mouseDragged() method
will create an element using the current cursor position and the position saved in start , and store a
reference to it in the tempElement member of the class. The last member will be used to store the
cursor position when mouseDragged() is called. Both start and last are of type Point since this
is the type that we will 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 process ends when you
release the mouse button, causing the mouseReleased() method to be called.
An object of type MouseHandler will be the listener for mouse events for the view object, so we
should put this in place in the SketchView constructor. Add the following code at the end of the
existing code:
public SketchView(Sketcher theApp) {
this.theApp = theApp;
MouseHandler handler = new MouseHandler(); // create the mouse listener
addMouseListener(handler); // Listen for button events
Search WWH ::




Custom Search