20-CS-694 Advanced Programming Techniques Spring 2012
Using update

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

     Previous      Next    Applet Source      All lectures

Repainting with Clipping and Double Buffering

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

public class CheckersDouble extends Applet implements Runnable {
   Thread runner;
   int xpos;
   int ux1, ux2;
   Image offscreenImg;
   Graphics offscreenGraphics;

   public void init() {
      offscreenImg = createImage(this.getSize().width, this.getSize().height);
      offscreenGraphics = offscreenImg.getGraphics();
   }

   public void start() {
      if (runner == null) {
         runner = new Thread(this);
         runner.start();
      }
   }

   public void run() {
      setBackground(Color.blue);
      while (true) {
         for (xpos=5 ; xpos < = 105; xpos += 4) {
            ux2 = xpos + 90;
            repaint();
            try { runner.sleep(50); } catch (InterruptedException e) {}
            if (ux1 == 0) ux1 = xpos;
         }
         for (xpos=105 ; xpos > 5; xpos -= 4) {
            ux1 = xpos;
            repaint();
            try { runner.sleep(50); } catch (InterruptedException e) {}
            if (ux2 == 0) ux2 = xpos + 90;
         }
      }
   }

   public void update(Graphics g) {
      g.clipRect(ux1, 5, ux2-ux1, 95);
      paint(g);
   }

   public void paint(Graphics g) {
      offscreenGraphics.setColor(Color.black);
      offscreenGraphics.fillRect(0,0,100,100);
      offscreenGraphics.setColor(Color.white);
      offscreenGraphics.fillRect(101,0,100,100);

      offscreenGraphics.setColor(Color.red);
      offscreenGraphics.fillOval(xpos,5,90,90);

      g.drawImage(offscreenImg, 0,0,this);
      ux1 = ux2 = 0;
   }
}