-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBounce.java
69 lines (61 loc) · 1.79 KB
/
Bounce.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package bounce;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
/**
* Shows an animated bouncing ball.
*
* @author Cay Horstmann
* @version 1.34 2015-06-21
*/
public class Bounce {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
/**
* The frame with ball component and buttons.
*/
class BounceFrame extends JFrame {
public static final int STEPS = 1000;
public static final int DELAY = 3;
private BallComponent comp;
/**
* Constructs the frame with the component for showing the bouncing ball and
* Start and Close buttons
*/
public BounceFrame() {
setTitle("Bounce");
comp = new BallComponent();
add(comp, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel, "Start", e -> addBall());
addButton(buttonPanel, "Close", e -> System.exit(0));
add(buttonPanel, BorderLayout.SOUTH);
pack();
}
public void addButton(Container container, String title, ActionListener listener) {
JButton button = new JButton(title);
container.add(button);
button.addActionListener(listener);
}
/**
* Adds a bouncing ball to the panel and makes it bounce 1,000 times.
*/
private void addBall() {
try {
Ball ball = new Ball();
comp.add(ball);
for (int i = 1; i <= STEPS; i++) {
ball.move(comp.getBounds());
comp.paint(comp.getGraphics());
Thread.sleep(DELAY);
}
} catch (InterruptedException ignored) {
}
}
}