public class BouncerApplet1 extends Applet
class Ball1
1: //BouncerApplet1.java
2: //A Start button starts a red ball bouncing around
3: //within a square. Does not use the Thread class,
4: //except to call the sleep() method.
6: import java.awt.*;
7: import java.applet.Applet;
8: import java.awt.event.*;
10: public class BouncerApplet1 extends Applet
11: implements ActionListener
12: {
13: private Button startButton;
14:
15: public void init()
16: {
17: startButton = new Button("Start");
18: add(startButton);
19: startButton.addActionListener(this);
20: }
22: public void actionPerformed(ActionEvent event)
23: {
24: if (event.getSource() == startButton)
25: {
26: Graphics g = getGraphics();
27: Ball1 ball = new Ball1(g);
28: ball.display();
29: }
30: }
31: }
33: class Ball1
34: {
35: private Graphics g;
36: private int x = 7, xChange = 7;
37: private int y = 0, yChange = 2;
38: private int diameter = 10;
39: private int rectLeftX = 0, rectRightX = 100;
40: private int rectTopY = 0, rectBottomY = 100;
42: public Ball1(Graphics graphics)
43: {
44: g = graphics;
45: }
47: public void display()
48: {
49: g.drawRect(rectLeftX+5, rectTopY,
50: rectRightX-rectLeftX-5,
51: rectBottomY-rectTopY);
53: for (int n=1; n<=100; n++)
54: {
55: g.setColor(Color.white);
56: g.fillOval (x, y, diameter, diameter);
57: if (x + xChange <= rectLeftX) xChange = -xChange;
58: if (x + xChange >= rectRightX-8) xChange = -xChange;
59: if (y + yChange <= rectTopY) yChange = -yChange;
60: if (y + yChange >= rectBottomY-7) yChange = -yChange;
61: x = x + xChange;
62: y = y + yChange;
63: g.setColor(Color.red);
64: g.fillOval (x, y, diameter, diameter);
66: try
67: {
68: Thread.sleep(100);
69: }
70: catch (InterruptedException e)
71: {
72: System.err.println("Sleep interrupted!");
73: }
74: }
75: }
76: }