Java Reference
In-Depth Information
Now that our
ActionListener
code is complete, we have to create and start the
timer that invokes the listener. Let's add code for the timer to the constructor for the
AnimatedRectPanel
:
// set up timer to animate rectangles every 100 ms
Timer time = new Timer(100, this);
time.start();
Here's the complete second version of the
AnimatedRectPanel
program that
incorporates all of these features:
1 // A panel that draws animated rectangles on its surface.
2
3
import
java.awt.*;
4
import
java.awt.event.*;
5
import
javax.swing.*;
6
7
public class
AnimatedRectPanel2
extends
JPanel
8
implements
ActionListener {
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
AnimatedRectPanel2() {
15 p1 =
new
Point(20, 40);
16 p2 =
new
Point(60, 10);
17 dx = 5;
18 dy = 5;
19
20 // set up timer to animate rectangles every 100 ms
21 Timer time =
new
Timer(100,
this
);
22 time.start();
23 }
24
25 // draws two rectangles on this panel on the screen
26
public void
paintComponent(Graphics g) {
27
super
.paintComponent(g); // call JPanel's version
28 g.setColor(Color.RED);
29 g.fillRect(p1.x, p1.y, 70, 30);
30 g.setColor(Color.BLUE);
31 g.fillRect(p2.x, p2.y, 20, 80);
32 }
Search WWH ::
Custom Search