public class BouncingBallCanvas
1:
2: import java.awt.*;
3: import javax.swing.*;
4:
5: public class BouncingBallCanvas
6: extends JPanel {
7:
8: public BouncingBallCanvas() {
9: super(true); // double-buffered
10: }
11:
12: public void initCanvas() {
13: d = getSize();
14: x = d.width * 2 / 3 ;
15: y = d.height - radius;
16: }
17:
18: public void paint(Graphics g) {
19: g.setColor(Color.white);
20: g.fillRect(0, 0, d.width, d.height);
21: if (x < radius || x > d.width - radius)
22: dx = -dx;
23: if (y < radius || y > d.height - radius)
24: dy = -dy;
25: x += dx; y += dy;
26: g.setColor(ballcolor);
27: g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
28: }
29:
30: public void setBallColor(Color c) {
31: ballcolor = c;
32: }
33:
34: public void setBallPosition(int x, int y) {
35: this.x = x; this.y = y;
36: }
37:
38: protected int x, y, dx = -2, dy = -4, radius = 20;
39: protected Color ballcolor = Color.red;
40: protected Dimension d;
41:
42: }