public class BounceApplet3
class Ball3 extends Thread
1: //BounceApplet3.java
2: //Demonstrates a bouncing ball, with a Start button.
3: //This time the Ball class actually inherits from Thread.
5: import java.awt.*;
6: import java.awt.event.*;
7: import java.applet.Applet;
10: public class BounceApplet3
11: extends Applet
12: implements ActionListener
13: {
14: private Button start;
16: public void init()
17: {
18: start = new Button("Start");
19: add(start);
20: start.addActionListener(this);
21: }
23: public void actionPerformed(ActionEvent event)
24: {
25: if (event.getSource() == start)
26: {
27: Graphics g = getGraphics();
28: Ball3 ball = new Ball3(g);
29: ball.start();
30: }
31: }
32: }
34:
35: class Ball3 extends Thread
36: {
37: private Graphics g;
39: // Set rectangle and ball sizes
40: private int x = 150, xChange = 7;
41: private int y = 90, yChange = 3;
42: private int diameter = 10;
44: // Set initial ball position
45: private int leftX = 100, rightX = 200;
46: private int topY = 40, bottomY = 140;
49: public Ball3(Graphics graphics)
50: {
51: g = graphics;
52: }
54: public void run()
55: {
56: g.setColor(Color.white);
57: g.fillRect(leftX, topY, rightX-leftX, bottomY-topY);
58: Color backgroundColor = g.getColor();
59: for (int n=1; n<300; n++)
60: {
61: g.setColor(backgroundColor);
62: g.fillOval(x, y, diameter, diameter);
64: if (x<=leftX || x>=rightX) xChange = -xChange;
65: if (y<=topY || y>=bottomY) yChange = -yChange;
66: x = x + xChange;
67: y = y + yChange;
69: g.setColor(Color.red);
70: g.fillOval(x, y, diameter, diameter);
71: try
72: {
73: sleep(30);
74: }
75: catch (InterruptedException e)
76: {
77: System.err.println("Exception: " + e.toString());
78: }
79: }
80: }
81: }