package bouncingball; import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*; public class Applet1 extends Applet implements ActionListener { private Balls ball; private Button start, stop; public void init() { start = new Button("Start"); add(start); start.addActionListener(this); stop = new Button("Stop"); add(stop); stop.addActionListener(this); } public void actionPerformed(ActionEvent event) { if(event.getSource() == start) { Graphics g = getGraphics(); ball = new Balls(g); ball.start(); } if(event.getSource() == stop) ball.pleaseStop(); } } class Balls extends Thread { boolean keepGoing; private Graphics g; private int x = 45, xChange = 20; private int y = 42, yChange = 15; private int diameter = 12; private int rectLeftX = 20, rectRightX = 285; private int rectTopY = 40, rectBottomY = 280; public Balls (Graphics graphics) { g = graphics; keepGoing = true; } public void pleaseStop() { keepGoing = false; } public void run() { g.setColor(Color.white); g.fillRect( rectLeftX, rectTopY, rectRightX - rectLeftX, rectBottomY - rectTopY); g.setColor(Color.black); g.drawRect( rectLeftX, rectTopY, rectRightX - rectLeftX, rectBottomY - rectTopY); while(keepGoing) { g.setColor(Color.white); g.fillOval(x, y, diameter, diameter); if ( x + xChange <= rectLeftX) xChange = -xChange; if ( x + xChange >= rectRightX) xChange = -xChange; if (y + yChange <= rectTopY) yChange = -yChange; if (y + yChange >= rectBottomY) yChange = -yChange; x += xChange; y += yChange; g.setColor(Color.red); g.fillOval(x, y, diameter, diameter); try { Thread.sleep(60); } catch (InterruptedException e) { System.err.println("sleep exception"); } } } }