public class BouncerApplet3 extends Applet
class Ball3 extends Thread
1: //BouncerApplet3.java
2: //A Start button starts a red ball bouncing around
3: //within a square and a Stop button stops it. Here
4: //the Ball3 class extends the Thread class and
5: //overrides its run() method.
7: import java.awt.*;
8: import java.applet.Applet;
9: import java.awt.event.*;
11: public class BouncerApplet3 extends Applet
12: implements ActionListener
13: {
14: private Button startButton, stopButton;
15: private Ball3 ball;
17: public void init()
18: {
19: startButton = new Button("Start");
20: stopButton = new Button("Stop");
21: stopButton.addActionListener(this);
22: startButton.addActionListener(this);
23: add(startButton);
24: add(stopButton);
25: }
27: public void actionPerformed(ActionEvent event)
28: {
29: if (event.getSource() == startButton)
30: {
31: Graphics g = getGraphics();
32: ball = new Ball3(g);
33: ball.start();
34: }
35: if (event.getSource() == stopButton)
36: ball.pleaseStop();
37: }
38: }
40: class Ball3 extends Thread
41: {
42: private boolean keepGoing;
43: private Graphics g;
44: private int x = 7, xChange = 7;
45: private int y = 0, yChange = 2;
46: private int diameter = 10;
47: private int rectLeftX = 0, rectRightX = 100;
48: private int rectTopY = 0, rectBottomY = 100;
50: public Ball3(Graphics graphics)
51: {
52: g = graphics;
53: keepGoing = true;
54: }
56: public void pleaseStop()
57: {
58: keepGoing = false;
59: }
61: public void run()
62: {
63: g.drawRect(rectLeftX+5, rectTopY,
64: rectRightX-rectLeftX-5,
65: rectBottomY-rectTopY);
67: while (keepGoing)
68: {
69: g.setColor(Color.white);
70: g.fillOval (x, y, diameter, diameter);
71: if (x + xChange <= rectLeftX) xChange = -xChange;
72: if (x + xChange >= rectRightX-8) xChange = -xChange;
73: if (y + yChange <= rectTopY) yChange = -yChange;
74: if (y + yChange >= rectBottomY-7) yChange = -yChange;
75: x = x + xChange;
76: y = y + yChange;
77: g.setColor(Color.red);
78: g.fillOval (x, y, diameter, diameter);
80: try
81: {
82: sleep(50);
83: }
84: catch (InterruptedException e)
85: {
86: System.err.println("Sleep interrupted!");
87: }
88: }
89: }
90: }