animateball.java

来自「Java 入门书的源码」· Java 代码 · 共 46 行

JAVA
46
字号
//Copyright (c) 1998, Arthur Gittleman
//This example is provided WITHOUT ANY WARRANTY either expressed or implied.

/* Animates a ball, moving it until the applet
 * quits.  Uses a thread to allow the system to
 * continue other processing.
 */

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

public class AnimateBall extends Applet
                       implements Runnable {
  private int x, y;
  private boolean done;

  public void start() {
    x = 50; y = 50; 
    done = false;
    Thread t = new Thread(this);
    t.start();
  }
  public void stop() {
    done = true;
  }
  public void paint(Graphics g) {
    g.fillOval(x,y,40,40);
  }
  public void run() {
      int dx=9, dy=9;
      while (true) {
        for(int i=0; i<10; i++) {
          if (done) return;
          x+=dx;
          y+=dy;
          repaint();
          try {
            Thread.sleep(300);
          }catch(InterruptedException e) {
             e.printStackTrace();
          }   
        }
        dx = -dx; dy = -dy; 
      }
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?