moveball.java

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

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

/* Uses a thread to move a ball ten times 
 * when the user presses a button. 
 */

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

public class MoveBall extends Applet 
                     implements ActionListener, Runnable {
  private int x = 50, y = 50;
  private Button move;

  public void init() {
    move = new Button("Move");
    add(move);
    move.addActionListener(this);
  }
  public void actionPerformed(ActionEvent event) {
    x = 50; y= 50;
    Thread t = new Thread(this);
    t.start();
  }
  public void paint(Graphics g) {
    g.fillOval(x,y,40,40);
  }
  public void run() {
    for(int i=0; i<10; i++) {
      x+=9;
      y+=9;
      repaint();
      try {
        Thread.sleep(300);
      }catch(InterruptedException e) {
         e.printStackTrace();
      }   
    }
  }
}

⌨️ 快捷键说明

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