playball.java

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

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

/* Add sounds to the AnimateBall applet 
 * of Example 11.5.
 */

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

public class PlayBall extends Applet
                       implements Runnable {
  private int x, y;
  private boolean done;
  private URL boomURL;
  AudioClip whistle;
 
  public void init() {
    try {
       URL url1 = new URL(getDocumentBase(),"whistle.au");
       boomURL = new URL(getCodeBase(),"boom.au");
       whistle = getAudioClip(url1);
    }catch (MalformedURLException e) {
         e.printStackTrace();
    } 
  }

  public void start() {
    x = 50; y = 50; 
    done = false;
    Thread t = new Thread(this);
    t.start();
    Sound sound = new Sound(whistle);
    sound.start();
  }
  public void stop() {
    done = true;
    whistle.stop();
  }
  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;
          play(boomURL);
          repaint();
          try {
            Thread.sleep(1000);
          }catch(InterruptedException e) {
             e.printStackTrace();
          }   
        }
        dx = -dx; dy = -dy; 
      }
  }
}
class Sound extends Thread {
  AudioClip clip;
  public Sound(AudioClip a) {
      clip = a;
  }
  public void run() {
    clip.loop();
  }
}     

⌨️ 快捷键说明

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