import java.applet.Applet; import java.applet.AudioClip; import java.awt.*; public class MovingBall extends Applet implements Runnable { int width, height; int r = 30; int x, y; int moveX = 3, moveY = 3; Thread thread; AudioClip au; public void init() { width = this.size().width; height = this.size().height; x = r; y = height / 2; setBackground(Color.blue); setForeground(Color.yellow); String audiofile = getParameter("audiofile"); if (audiofile != null) { au = getAudioClip(getDocumentBase(), audiofile); } } public void start() { if (thread == null) { thread = new Thread(this); thread.start(); } } public void stop() { if (thread != null) { thread.stop(); thread = null; } } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { g.fillOval(x, y, r, r); } public void run() { while(true) { try { Thread.sleep(10); } catch (InterruptedException e) { break; } x += moveX; y += moveY; if (x <= 0 || x >= width - r) { moveX *= -1; au.play(); } if (y <= 0 || y >= height - r) { moveY *= -1; au.play(); } repaint(); } } }