Clearing Rectangles

It is also possible to clear a rectangle that you've drawn. The syntax is exactly what you'd expect:

public abstract void clearRect(int x, int y, int width, int height)

This program uses clearRect() to blink a rectangle on the screen.

import java.applet.*;    
import java.awt.*; 

public class Blink extends Applet {

  public void paint(Graphics g) {

    int appletHeight = this.getSize().height;
    int appletWidth  = this.getSize().width;
    int rectHeight   = appletHeight/3;
    int rectWidth    = appletWidth/3;
    int rectTop      = (appletHeight - rectHeight)/2;
    int rectLeft     = (appletWidth - rectWidth)/2;

    for (int i=0; i < 1000; i++) {
      g.fillRect(rectLeft, rectTop, rectWidth-1, rectHeight-1);
      g.clearRect(rectLeft, rectTop, rectWidth-1, rectHeight-1);
    }
    
  }

}

This is not how you should do animation in practice, but this is the best we can do until we introduce threads.


Previous | Next | Top | Cafe au Lait

Copyright 1997-1999 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified October 21, 1999