Option 3: Have Routines Other Than paint Directly Do Drawing Operations

1. Idea

Arbitrary methods can call getGraphics to obtain the window’s Graphics object, then use that to draw temporarily.

2. Example Rubberband.java: (Download Source)

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/** Draw "rubberband" rectangles when the user drags the mouse. */

public class Rubberband extends Applet {
  private int startX, startY, lastX, lastY;
  
  public void init() {
    addMouseListener(new RectRecorder());
    addMouseMotionListener(new RectDrawer());
    setBackground(Color.white);
  }  

  /** Draw the rectangle, adjusting the x, y, w, h
   *  to correctly accomadate for the opposite corner of the 
   *  rubberband box relative to the start position
   */
  private void drawRectangle(Graphics g, int startX, int startY,
                             int stopX, int stopY ) {
    int x, y, w, h;
    x = Math.min(startX, stopX);
    y = Math.min(startY, stopY);
    w = Math.abs(startX - stopX);
    h = Math.abs(startY - stopY);
    g.drawRect(x, y, w, h);
  }

  private class RectRecorder extends MouseAdapter {
    /** When the user presses the mouse, record the
     *  location of the top-left corner of rectangle.
     */
    public void mousePressed(MouseEvent event) {
      startX = event.getX();
      startY = event.getY();
      lastX = startX;
      lastY = startY;
    }

    /** Erase the last rectangle when the user releases
     *  the mouse.
     */
    public void mouseReleased(MouseEvent event) {
      Graphics g = getGraphics();
      g.setXORMode(Color.lightGray);
      drawRectangle(g, startX, startY, lastX, lastY);
    }
  } // End RectRecorder inner class

  private class RectDrawer extends MouseMotionAdapter {
    /** This draws a rubberband rectangle, from the location 
     *  where the mouse was first clicked to the location
     *  where the mouse is dragged.
     */
    public void mouseDragged(MouseEvent event) {
      int x = event.getX();
      int y = event.getY();
      Graphics g = getGraphics();
      g.setXORMode(Color.lightGray);
      drawRectangle(g, startX, startY, lastX, lastY);
      drawRectangle(g, startX, startY, x, y);
      lastX = x;
      lastY = y;
    }
  } // End RectDrawer inner class
}

3. Rubberband Output

© 1996-2000 Marty Hall, 1999-2000 Lawrence M. Brown