1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
   |  
 
// OnTheFarm Class
// OnTheFarm.java
 
// Imports
import java.applet.*;
import java.awt.*;
import java.util.Random;
 
public class OnTheFarm extends Applet implements Runnable {
  AudioClip clip[] = new AudioClip[8];
  Thread    thread;
  Random    rand = new Random(System.currentTimeMillis());
 
  public void init() {
    // Load the sounds
    clip[0] = getAudioClip(getDocumentBase(), "Res/Hillbilly.au");
    clip[1] = getAudioClip(getDocumentBase(), "Res/Cow.au");
    clip[2] = getAudioClip(getDocumentBase(), "Res/Duck.au");
    clip[3] = getAudioClip(getDocumentBase(), "Res/Goat.au");
    clip[4] = getAudioClip(getDocumentBase(), "Res/Hen.au");
    clip[5] = getAudioClip(getDocumentBase(), "Res/Horse.au");
    clip[6] = getAudioClip(getDocumentBase(), "Res/Pig.au");
    clip[7] = getAudioClip(getDocumentBase(), "Res/Rooster.au");
  }
 
  public void start() {
    if (thread == null) {
      thread = new Thread(this);
      thread.start();
    }
  }
 
  public void stop() {
    if (thread != null) {
      thread.stop();
      thread = null;
    }
  }
 
  public void run() {
    while (Thread.currentThread() == thread) {
      // Loop the music sound
      clip[0].loop();
 
      while (true) {
        // Wait three seconds
        try
          Thread.sleep(3000);
        catch (InterruptedException e)
          break;
 
        // Play an animal sound
        clip[(rand.nextInt() % 3) + 4].play();
      }
    }
  }
 
  public void paint(Graphics g) {
    Font        font = new Font("TimesRoman", Font.PLAIN, 20);
    FontMetrics fm = g.getFontMetrics(font);
    String      str = new String("On the farm...");
    g.setFont(font);
    g.drawString(str, (size().width - fm.stringWidth(str)) / 2,
      ((size().height - fm.getHeight()) / 2) + fm.getAscent());
  }
} | 
Partager