19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

626 Chapter 16 Event-Driven <strong>Programming</strong><br />

javax.swing.Timer<br />

+Timer(delay: int, listener:<br />

ActionListener)<br />

+addActionListener(listener:<br />

ActionListener): void<br />

+start(): void<br />

+s<strong>to</strong>p(): void<br />

+setDelay(delay: int): void<br />

Creates a Timer object with a specified delay in milliseconds and an<br />

ActionListener.<br />

Adds an ActionListener <strong>to</strong> the timer.<br />

Starts this timer.<br />

S<strong>to</strong>ps this timer.<br />

Sets a new delay value for this timer.<br />

FIGURE 16.18<br />

A Timer object fires an ActionEvent at a fixed rate.<br />

The Timer class can be used <strong>to</strong> control animations. Listing 16.11 gives a program that<br />

displays two messages in separate panels (see Figure 16.19). You can use the mouse but<strong>to</strong>n <strong>to</strong><br />

control the animation speed for each message. The speed increases when the left mouse<br />

but<strong>to</strong>n is clicked and decreases when the right but<strong>to</strong>n is clicked.<br />

FIGURE 16.19<br />

Two messages move in the panels.<br />

create message panel<br />

create timer<br />

LISTING 16.11<br />

AnimationDemo.java<br />

1 import java.awt.*;<br />

2 import java.awt.event.*;<br />

3 import javax.swing.*;<br />

4<br />

5 public class AnimationDemo extends JFrame {<br />

6 public AnimationDemo() {<br />

7 // Create two MovingMessagePanel for displaying two moving messages<br />

8 this.setLayout(new GridLayout(2, 1));<br />

9 add(new MovingMessagePanel("message 1 moving?"));<br />

10 add(new MovingMessagePanel("message 2 moving?"));<br />

11 }<br />

12<br />

13 /** Main method */<br />

14 public static void main(String[] args) {<br />

15 AnimationDemo frame = new AnimationDemo();<br />

16 frame.setTitle("AnimationDemo");<br />

17 frame.setLocationRelativeTo(null); // Center the frame<br />

18 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br />

19 frame.setSize(280, 100);<br />

20 frame.setVisible(true);<br />

21 }<br />

22<br />

23 // Inner class: Displaying a moving message<br />

24 static class MovingMessagePanel extends JPanel {<br />

25 private String message = "Wel<strong>com</strong>e <strong>to</strong> <strong>Java</strong>";<br />

26 private int xCoordinate = 0;<br />

27 private int yCoordinate = 20;<br />

28 private Timer timer = new Timer(1000, new TimerListener());

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!