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; int lastPaintedX, lastPaintedY; 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); } lastPaintedX = x; lastPaintedY = y; } 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) { int minX = x < lastPaintedX ? x : lastPaintedX; int maxX = x > lastPaintedX ? x : lastPaintedX; int minY = y < lastPaintedY ? y : lastPaintedY; int maxY = y > lastPaintedY ? y : lastPaintedY; g.clipRect(minX, minY, maxX - minX + r, maxY - minY + r); g.setColor(getBackground()); g.fillRect(0, 0, width, height); paint(g); } public void paint(Graphics g) { g.setColor(getForeground()); g.fillOval(x, y, r, r); lastPaintedX = x; lastPaintedY = y; } 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(); } } }