Java Reference
In-Depth Information
The repaint method causes a component to repaint itself. Call this method
whenever you modify the shapes that the paintComponent method draws.
The actionPerformed method of the timer listener simply calls
component.moveBy(1, 1) . This moves the rectangle one pixel down and to the
right. Since the actionPerformed method is called many times per second, the
rectangle appears to move smoothly across the frame.
ch09/timer/RectangleMover.java
1 import java.awt.event.ActionEvent;
2 import java.awt.event.ActionListener;
3 import javax.swing.JFrame;
4 import javax.swing.Timer;
5
6 /**
7 This program moves the rectangle.
8 */
9 public class RectangleMover
10 {
11 public static void main(String[] args)
12 {
13 JFrame frame = new JFrame();
14
15 frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
16 frame.setTitle( "An animated rectangle" );
17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE
18
19 final RectangleComponent component = new
RectangleComponent();
20 frame.add(component);
21
22 frame.setVisible( true );
23
24 class TimerListener implements
ActionListener
25 {
26 public void
actionPerformed(ActionEvent event)
27 {
28 component.moveBy( 1 , 1 );
Search WWH ::




Custom Search