import java.util.ArrayList; import uwcse.graphics.*; import java.awt.Color; /** * In a graphics window, place at random location a square when a key * is pressed on the keyboard. Delete that square if it is clicked with * the mouse. Keep track of the squares with an ArrayList */ public class ArrayListExample extends GWindowEventAdapter { // Keep the list of squares in an ArrayList private ArrayList squareList; // The graphics window private GWindow window; // length of the side of the squares private int side = 20; /** * Initialize the graphics window and the list of squares */ public ArrayListExample() { // Create the graphics window window = new GWindow("Array list example",400,400); window.setExitOnClose(); // Send all of the events to this ArrayListExample window.addEventHandler(this); // Create the square list (initially empty) squareList = new ArrayList(); } /** * A key has been pressed. Create a square at a random location. */ public void keyPressed(GWindowEvent e) { // Center of the square int x = (int)(Math.random()*400); int y = (int)(Math.random()*400); // Color of the square (random) Color c = new Color((float)Math.random(), (float)Math.random(), (float)Math.random()); // Create the square Rectangle r = new Rectangle(x-side/2,y-side/2,side,side,c,true); squareList.add(r); window.add(r); // Show it window.doRepaint(); } /** * Mouse click on the window. If it is on a square, erase that square */ public void mousePressed(GWindowEvent e) { // Iterate over the squares (from the last one to the first one) for(int i=squareList.size()-1; i>=0; i--) { // Is the click on element i of squareList? Rectangle r = (Rectangle)(squareList.get(i)); int x = e.getX(); int y = e.getY(); if (x>=r.getX() && x<=r.getX()+r.getWidth() && y>=r.getY() && y<=r.getY()+r.getHeight()) { window.remove(r); squareList.remove(i); window.doRepaint(); return; } } } }