Izboljšan primer


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

public class Nit2 extends Applet implements Runnable{
 
  Thread nit=null;
  int w, h;
  int x, y;
  int radius = 20;
  int dx , dy, ds;

  Image offImage;
  Graphics offGraphics;

  //***************************************************
  public void init(){
 x = radius; y = radius;
        ds = 5;
        dx = ds; dy = ds;
        w = this.getSize().width;
        h = this.getSize().height;
        offImage=createImage(w,h);
        offGraphics=offImage.getGraphics();
        this.setBackground(Color.blue);
  }
  //***************************************************
  public void paint(Graphics g){
     draw(offGraphics);
     g.drawImage(offImage,0,0,this);
  }

 void draw(Graphics g){
      g.setColor(Color.blue);
      g.fillRect(0,0,w,h);
      g.setColor(Color.yellow);
      g.fillOval(x-radius,y-radius, 2*radius, 2*radius);
  }
//*****************************************************
public void start(){
    if(nit==null){
        nit =new Thread(this);
        nit.start();
    }
}

//*****************************************************
public void run(){
   while(nit != null){
      try {nit.sleep(50);}catch(InterruptedException e){}
      x = x + dx;
      y = y + dy;
      if (x > (w - radius)) {
   x = w - radius; dx = -ds;
      }
      if (y > (h - radius)) {
   y = h - radius; dy = -ds;
      }
      if (x < radius) {
          x = radius; dx = ds;
      }
      if (y < radius) {
          y = radius; dy = ds;
      }
      repaint();
   }
}

//*****************************************************
  public void stop(){
     if(nit != null) nit.stop();
     nit=null;
  }
 

}