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; 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); } lastPaintedX = x; lastPaintedY = y; if (off_g == null) { off_im = createImage(width, height); off_g = off_im.getGraphics(); off_g.setColor(getBackground()); off_g.fillRect(0, 0, width, height); } } 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; off_g.clipRect(minX, minY, maxX - minX + r, maxY - minY + r); g.clipRect(minX, minY, maxX - minX + r, maxY - minY + r); off_g.setColor(getBackground()); off_g.fillRect(0, 0, width, height); paint(g); } public void paint(Graphics g) { off_g.setColor(getForeground()); off_g.fillOval(x, y, r, r); g.drawImage(off_im, 0, 0, this); 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(); } } }