-
Notifications
You must be signed in to change notification settings - Fork 0
/
AnimatedApplet.java
100 lines (87 loc) · 2.68 KB
/
AnimatedApplet.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public static void main(String[] args) {
public class AnimatedApplet extends Applet implements Runnable, ActionListener {
private Thread animatorThread;
private int x, y;
private int dx, dy;
private int delay = 50; // milliseconds
private boolean running = false;
private Button startButton, stopButton, fasterButton, slowerButton;
public void init() {
// Initialize object position and velocity
x = 100;
y = 100;
dx = 2;
dy = 2;
// Create buttons for controlling the animation
startButton = new Button("Start");
stopButton = new Button("Stop");
fasterButton = new Button("Faster");
slowerButton = new Button("Slower");
// Add action listeners to buttons
startButton.addActionListener(this);
stopButton.addActionListener(this);
fasterButton.addActionListener(this);
slowerButton.addActionListener(this);
// Add buttons to the applet
add(startButton);
add(stopButton);
add(fasterButton);
add(slowerButton);
}
public void start() {
// Start the animation thread
if (animatorThread == null) {
running = true;
animatorThread = new Thread(this);
animatorThread.start();
}
}
public void stop() {
// Stop the animation thread
running = false;
animatorThread = null;
}
public void run() {
while (running) {
// Update object position
x += dx;
y += dy;
// Bounce off walls
if (x <= 0 || x >= getWidth()) {
dx = -dx;
}
if (y <= 0 || y >= getHeight()) {
dy = -dy;
}
// Repaint the applet
repaint();
// Delay for smooth animation
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void paint(Graphics g) {
// Draw a moving object
g.setColor(Color.RED);
g.fillOval(x - 10, y - 10, 20, 20);
}
public void actionPerformed(ActionEvent e) {
// Handle button clicks
if (e.getSource() == startButton) {
start();
} else if (e.getSource() == stopButton) {
stop();
} else if (e.getSource() == fasterButton) {
delay -= 5; // Decrease delay for faster animation
} else if (e.getSource() == slowerButton) {
delay += 5; // Increase delay for slower animation
}
}
}
}