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