import uwcse.graphics.*; import java.awt.Color; import java.util.*; // Display some graphics at the location of the mouse click // (here a filled circle of radius 30. The color of the circle is random) public class MouseHandler extends GWindowEventAdapter { // Graphics window private GWindow window; // Keep track of the circles in an ArrayList private ArrayList circles = new ArrayList(); // Are we adding circles to the window? boolean isInAddMode = true; public MouseHandler() { // Create a graphics window this.window = new GWindow("Using the mouse",400,400); // Terminate the application when closing the window this.window.setExitOnClose(); // Send all of the events to this MouseHandler this.window.addEventHandler(this); } // Method to manage the mouse clicks /** * Invoked when a mouse button has been pressed on the window. */ public void mousePressed(GWindowEvent e) { // mouse coordinates int x = e.getX(); int y = e.getY(); // Print the mouse coordinates System.out.println("x="+x+" y="+y); // Display a circle of radius 30 // centered at the click location. // The color of the circle is random. if (this.isInAddMode) { Random r = new Random(System.currentTimeMillis()); Color c = new Color(r.nextFloat(),r.nextFloat(), r.nextFloat()); Oval circle = new Oval(x-30,y-30,60,60,c,true); this.circles.add(circle); this.window.add(circle); } else { // erase the circle where the click is (if there // is such a circle) for(int i=circles.size()-1; i>=0; i--) { Oval circle = (Oval)circles.get(i); // center of the circle int xc = circle.getX()+circle.getWidth()/2; int yc = circle.getY()+circle.getHeight()/2; // radius of the circle int r = circle.getWidth()/2; // Is (x,y) in the circle? if ( (x-xc)*(x-xc)+(y-yc)*(y-yc)<=r*r ) { window.remove(circle); circles.remove(circle); break; } } window.doRepaint(); } } /** * Toggle between add and erase mode by pressing * any key */ public void keyPressed(GWindowEvent e) { this.isInAddMode = !this.isInAddMode; } }