import java.awt.*; import java.applet.Applet; public class Asst7 extends Applet { DrawingCanvas canvas; public void init() { GridLayout grid = new GridLayout(1,0); setLayout(grid); add (new DrawingCanvas()); validate(); } } class DrawingCanvas extends Canvas { private Dimension rectangleSize; private int pressedX; private int pressedY; // constructor public DrawingCanvas() { super(); rectangleSize = null; pressedX = pressedY = -1; } // called when mouse button is pressed // (x,y) is position of mouse press // ignore the event parameter public boolean mouseDown(Event event, int x, int y) { // (for debugging purposes?) System.out.println ("mouse pressed at (" + x + ", " + y + ")"); pressedX = x; pressedY = y; repaint(); // asks system to call paint() sometime soon return false; } // called when mouse is moved while holding down the button public boolean mouseDrag(Event event, int x, int y) { rectangleSize = new Dimension(x-pressedX, y-pressedY); repaint(); return false; } // called when mouse button is released public boolean mouseUp(Event event, int x, int y) { rectangleSize = new Dimension(x-pressedX, y-pressedY); repaint(); return false; } public void paint(Graphics g) { Dimension d = size(); if (pressedX >= 0) { g.setColor(Color.blue); g.drawLine(0, pressedY, pressedX, pressedY); g.setColor(Color.red); g.drawLine(d.width, pressedY, pressedX, pressedY); g.setColor(Color.green); g.drawLine(pressedX, 0, pressedX, pressedY); g.setColor(Color.magenta); g.drawLine(pressedX, d.height, pressedX, pressedY); } if (rectangleSize != null) { g.setColor(Color.yellow); int x = pressedX; int y = pressedY; int w = rectangleSize.width - 1; int h = rectangleSize.height - 1; if (w < 0) { x += w; w *= -1; } if (h < 0) { y += h; h *= -1; } g.fillRect(x, y, w, h); } } }