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; Image off_im; Graphics off_g; 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); } if (off_g == null) { off_im = createImage(width, height); off_g = off_im.getGraphics(); } } 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) { off_g.setColor(getBackground()); off_g.fillRect(0, 0, width, height); off_g.setColor(getForeground()); off_g.fillOval(x, y, r, r); g.drawImage(off_im, 0, 0, this); } 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(); } } }