Java Reference
In-Depth Information
javax.swing.JPanel
javax.swing.JPanel
javax.swing.JApplet
1
1
11
Ball
BallControl
BounceBallApp
-x: int
-y: int
-dx: int
-dy: int
-radius: int
-delay: int
-timer: Timer
-ball: Ball
-jsbDelay: JScrollBar
-jbtResume: JButton
-jbtSuspend: JButton
+BounceBallApp()
+main(args: String[]): void
+BallControl()
+Ball()
+suspend(): void
+resume(): void
+setDelay(delay: int): void
F IGURE 18.9 BounceBallApp contains BallControl , and BallControl contains Ball .
L ISTING 18.7 Ball.java
1 import javax.swing.Timer;
2 import java.awt.*;
3 import javax.swing.*;
4 import java.awt.event.*;
5
6 public class Ball extends JPanel {
7
8
9
private int delay = 10 ;
timer delay
// Create a timer with the specified delay in milliseconds
10
11
12
private Timer timer = new Timer(delay, new TimerListener());
create timer
private int x = 0 ; private int y = 0 ; // Current ball position
13
private int radius = 5 ; // Ball radius
14
private int dx = 2 ; // Increment on ball's x-coordinate
15
private int dy = 2 ; // Increment on ball's y-coordinate
16
17
public Ball() {
18
19 }
20
21
22 @Override /** Handle the action event */
23
timer.start();
start timer
private class TimerListener implements ActionListener {
timer listener
public void actionPerformed(ActionEvent e) {
repaint ball
24
25 }
26 }
27
28 @Override
29
30
repaint();
protected void paintComponent(Graphics g) {
paint ball
super .paintComponent(g);
31
32 g.setColor(Color.red);
33
34 // Check boundaries
35 if (x < 0 || x > getWidth())
36 dx *= -1 ;
 
 
Search WWH ::




Custom Search