Java Reference
In-Depth Information
moving picture. A timer is an object that, once started, fires an action event at regular
intervals. You supply the timer with an
ActionListener
to use and a delay time in
milliseconds between action events, and it does the rest. You need to include two
objects to create an animation:
• An
ActionListener
object that updates the way the panel draws itself
•A
Timer
object to invoke the
ActionListener
object at regular intervals, caus-
ing the panel to animate
Let's modify our
RectPanel
class from the previous section to move its rectan-
gles on the panel. To make them move, we must store their positions as fields in the
JPanel
object. We'll repeatedly change the fields' values and redraw the rectangles
as the program is running, which will make it look like they're moving. We'll store
the desired change in
x
and change in
y
as fields called
dx
and
dy
, respectively.
Here's the code for our animated
RectPanel
:
1 // A panel that draws animated rectangles on its surface.
2 // Initial version-will change in the following section.
3
4
import
java.awt.*;
5
import
java.awt.event.*;
6
import
javax.swing.*;
7
8
public class
AnimatedRectPanel1
extends
JPanel {
9
private
Point p1; // location of first rectangle
10
private
Point p2; // location of second rectangle
11
private int
dx; // amount by which to move horizontally
12
private int
dy; // amount by which to move vertically
13
14
public
AnimatedRectPanel1() {
15 p1 =
new
Point(20, 40);
16 p2 =
new
Point(60, 10);
17 dx = 5;
18 dy = 5;
19 }
20
21 // draws the panel on the screen
22
public void
paintComponent(Graphics g) {
23
super
.paintComponent(g); // call JPanel's version
24 g.setColor(Color.RED);
25 g.fillRect(p1.x, p1.y, 70, 30);
26 g.setColor(Color.BLUE);
27 g.fillRect(p2.x, p2.y, 20, 80);
28 }
29 }
Search WWH ::
Custom Search