Java Reference
In-Depth Information
javax.swing.Timer
+Timer(delay: int, listener:
ActionListener)
+addActionListener(listener:
ActionListener): void
+start(): void
+stop(): void
+setDelay(delay: int): void
Creates a Timer object with a specified delay in milliseconds and an
ActionListener .
Adds an ActionListener to the timer.
Starts this timer.
Stops this timer.
Sets a new delay value for this timer.
F IGURE 16.18
A Timer object fires an ActionEvent at a fixed rate.
The Timer class can be used to control animations. Listing 16.11 gives a program that
displays two messages in separate panels (see Figure 16.19). You can use the mouse button to
control the animation speed for each message. The speed increases when the left mouse
button is clicked and decreases when the right button is clicked.
F IGURE 16.19
Two messages move in the panels.
L ISTING 16.11 AnimationDemo.java
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4
5 public class AnimationDemo extends JFrame {
6 public AnimationDemo() {
7 // Create two MovingMessagePanel for displaying two moving messages
8 this .setLayout( new GridLayout( 2 , 1 ));
9 add( new MovingMessagePanel( "message 1 moving?" ));
10 add( new MovingMessagePanel( "message 2 moving?" ));
11 }
12
13 /** Main method */
14 public static void main(String[] args) {
15 AnimationDemo frame = new AnimationDemo();
16 frame.setTitle( "AnimationDemo" );
17 frame.setLocationRelativeTo( null ); // Center the frame
18 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19 frame.setSize( 280 , 100 );
20 frame.setVisible( true );
21 }
22
23
create message panel
// Inner class: Displaying a moving message
24
static class MovingMessagePanel extends JPanel {
25
private String message = "Welcome to Java" ;
26
private int xCoordinate = 0 ;
27
private int yCoordinate = 20 ;
28
private Timer timer = new Timer( 1000 , new TimerListener());
create timer
 
 
Search WWH ::




Custom Search