import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Image;
import java.awt.Dimension;

/* <applet code="Main.class" width="500" height="500"></applet> */

class ForDimChange {
  private Dimension dim;
  private Image buff;
  private Graphics ct;
  private int x, y;
  private Applet applet;
  ForDimChange(Applet applet) {
    this.applet = applet;
    x = y = 0;
    this.update();
  }
  void update() {
    boolean flag = false;
    dim = applet.getSize();
    if (x != dim.width) {
      x = dim.width;      
      flag = true;
    }
    if (y != dim.height) {
      y = dim.height;
      flag = true;
    }
    if (flag) {
      buff = applet.createImage(x, y);
      ct = buff.getGraphics();
    }
  }
  int get_dimx() { return x; }
  int get_dimy() { return y; }  
  Image get_buff() { return buff; }
  Graphics get_ct() { return ct; }
}

public class Main extends Applet implements Runnable {
  final static int square_size = 20;
  final static int quantum = 5;
  boolean chkx = true, chky = true;
  int x = 250, y = 140;
  Thread th;
  ForDimChange fdc;

  public void init() {
    fdc = new ForDimChange(this);
    th = new Thread(this);
    th.start();
  }

  public void run() {
    try {
      while (true) {
        fdc.update();
        if (chkx) x++; else x--;
        if (chky) y++; else y--;
        if (x >= fdc.get_dimx() - square_size) chkx = false;
        if (x <= 0) chkx = true;
        if (y >= fdc.get_dimy() - square_size) chky = false;
        if (y <= 0) chky = true;

        repaint();
        Thread.sleep(quantum);
      }
    } catch (InterruptedException e) { };
  }
  public void update(Graphics g) {
    paint(g);
  }
  public void paint(Graphics g) {
    Graphics ct;
    ct = fdc.get_ct();
    ct.setColor(Color.white);
    ct.fillRect(0, 0, fdc.get_dimx(), fdc.get_dimy());
    ct.setColor(Color.red);
    ct.fillRect(x, y, square_size, square_size);
    g.drawImage(fdc.get_buff(), 0, 0, this);
  }
}
/* end */
