Java Reference
In-Depth Information
class MouseHandler extends MouseInputAdapter {
public void mousePressed(MouseEvent e) {
// Check if the cursor is inside any marker
if(ctrlQuad.contains(e.getX(), e.getY()))
selected = ctrlQuad;
else if(ctrlCubic1.contains(e.getX(), e.getY()))
selected = ctrlCubic1;
else if(ctrlCubic2.contains(e.getX(), e.getY()))
selected = ctrlCubic2;
}
public void mouseReleased(MouseEvent e) {
selected = null; // Deselect any selected marker
}
public void mouseDragged(MouseEvent e) {
if(selected != null) { // If a marker is selected
// Set the marker to current cursor position
selected.setLocation(e.getX(), e.getY());
pane.repaint(); // Redraw pane contents
}
}
Marker selected = null; // Stores reference to selected marker
}
We need to add two import statements to the beginning of the source file, one because we reference
the MouseInputAdapter class, and the other because we refer to the MouseEvent class:
import javax.swing.event.MouseInputAdapter;
import java.awt.event.MouseEvent;
The mousePressed() method calls a method contains() that should test whether the point defined
by the arguments is inside the marker. We can implement this in the Marker class like this:
// Test if a point x,y is inside the marker
public boolean contains(double x, double y) {
return circle.contains(x,y);
}
This just calls the contains() method for the circle object that is the marker. This will return true
if the point ( x , y ) is inside.
The mouseDragged() method calls a method setLocation() for the selected Marker object, so we
need to implement this in the Marker class, too:
// Sets a new control point location
public void setLocation(double x, double y) {
center.x = x; // Update control point
center.y = y; // coordinates
circle.x = x-radius; // Change circle position
Search WWH ::




Custom Search