// File DrawRect.java // // Author: Benjamin Lewis // Date: March 20, 1999 // // This applet allows the user to draw a rectangle by dragging the // mouse. The area of the rectangle will be shown in the status bar. // // Bugs: Some flicker while dragging the rectangle. Could be improved // somewhat by double-buffering the graphics. import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class DrawRect extends Applet { public final Color BACKGROUND_COLOR = Color.black; public final Color FOREGROUND_COLOR = Color.red; int x1 = 0; int x2 = 0; int y1 = 0; int y2 = 0; boolean rectangleSet = false; public void init() { // delegate the mouse listening to a new Mouse Listener RectMouseListener listener = new RectMouseListener(this); addMouseListener(listener); addMouseMotionListener(listener); // set up some pretty colors setBackground(BACKGROUND_COLOR); setForeground(FOREGROUND_COLOR); } public void drawRectangle() { // show the are of the rectangle on the status bar int area = Math.abs((x2-x1) * (y2-y1)); showStatus("Area of rectangle is "+area+" pixels"); rectangleSet = true; // a rectangle has been drawn repaint(); } public void paint(Graphics g) { if (rectangleSet) { // We don't know which way the user dragged the mouse... int startx = Math.min(x1, x2); int starty = Math.min(y1, y2); int width = Math.abs(x2 - x1); int height = Math.abs(y2 - y1); g.drawRect(startx, starty, width, height); } } } class RectMouseListener implements MouseListener, MouseMotionListener { DrawRect applet; public RectMouseListener(DrawRect applet) { this.applet = applet; } public void mouseMoved(MouseEvent e) { } public void mouseDragged(MouseEvent e) { applet.x2 = e.getX(); applet.y2 = e.getY(); applet.drawRectangle(); } public void mousePressed(MouseEvent e) { applet.x1 = e.getX(); applet.y1 = e.getY(); } public void mouseReleased(MouseEvent e) { applet.x2 = e.getX(); applet.y2 = e.getY(); applet.drawRectangle(); } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }