// CSE 143, Homework 1, Rectangle-Rama // This provided main program uses your RectangleManager class. // It display a DrawingPanel, creates several random Rectangle objects, // and adds them to your manager. It also listens for mouse clicks, notifying // your rectangle manager when the mouse buttons are pressed. // A left-click raises a rectangle to the top of the Z-order. // A Shift-left-click lowers a rectangle to the bottom of the Z-order. // A right-click (or a Ctrl-left-click for Mac people) deletes a rectangle. // A Shift-right-click (or a Shift-Ctrl-left-click for Mac people) deletes // all rectangles touching the mouse point. import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; public class RectangleMain { // constants for the drawing panel size, rectangle sizes, and # of rects public static final int WIDTH = 300; public static final int HEIGHT = 300; public static final int MIN_SIZE = 20; public static final int MAX_SIZE = 100; public static final int RECTANGLES = 20; public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(WIDTH, HEIGHT); Graphics g = panel.getGraphics(); // create several random rectangles and put them into a manager RectangleManager list = new RectangleManager(); for (int i = 0; i < RECTANGLES; i++) { // choose random coordinates Random rand = new Random(); int w = rand.nextInt(MAX_SIZE - MIN_SIZE + 1) + MIN_SIZE; int h = rand.nextInt(MAX_SIZE - MIN_SIZE + 1) + MIN_SIZE; int x = rand.nextInt(WIDTH - w); int y = rand.nextInt(HEIGHT - h); // choose random color int red = rand.nextInt(256); int green = rand.nextInt(256); int blue = rand.nextInt(256); Color color = new Color(red, green, blue); // add random rectangle to list Rectangle rect = new Rectangle(x, y, w, h, color); list.addRectangle(rect); } list.drawAll(g); // listen for mouse clicks RectangleMouseListener listener = new RectangleMouseListener(panel, list); panel.addMouseListener(listener); } // A class for responding to mouse clicks on the drawing panel. public static class RectangleMouseListener extends MouseInputAdapter { private DrawingPanel panel; private RectangleManager list; public RectangleMouseListener(DrawingPanel panel, RectangleManager list) { this.panel = panel; this.list = list; } public void mousePressed(MouseEvent event) { int x = event.getX(); int y = event.getY(); if (event.isControlDown() || SwingUtilities.isRightMouseButton(event)) { // treat right-clicks and control-left-clicks as the same (for Mac users) if (event.isShiftDown()) { list.deleteAll(x, y); } else { list.delete(x, y); } } else { if (event.isShiftDown()) { list.lower(x, y); } else { list.raise(x, y); } } // repaint all of the rectangles panel.clear(); Graphics g = panel.getGraphics(); list.drawAll(g); } } }