19.09.2015 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

clock display a new current time every second? The key <strong>to</strong> making the clock tick is <strong>to</strong> repaint<br />

it every second with a new current time. You can use a timer <strong>to</strong> control the repainting of the<br />

clock with the code in Listing 16.12.<br />

VideoNote<br />

Animate a clock<br />

create a clock<br />

create a timer<br />

start timer<br />

listener class<br />

implement handler<br />

set new time<br />

repaint<br />

LISTING 16.12<br />

ClockAnimation.java<br />

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

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

3<br />

4 public class ClockAnimation extends JFrame {<br />

5 private StillClock clock = new StillClock();<br />

6<br />

7 public ClockAnimation() {<br />

8 add(clock);<br />

9<br />

10 // Create a timer with delay 1000 ms<br />

11 Timer timer = new Timer(1000, new TimerListener());<br />

12 timer.start();<br />

13 }<br />

14<br />

15 private class TimerListener implements ActionListener {<br />

16 @Override /** Handle the action event */<br />

17 public void actionPerformed(ActionEvent e) {<br />

18 // Set new time and repaint the clock <strong>to</strong> display current time<br />

19 clock.setCurrentTime();<br />

20 clock.repaint();<br />

21 }<br />

22 }<br />

23<br />

24 /** Main method */<br />

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

26 JFrame frame = new ClockAnimation();<br />

27 frame.setTitle("ClockAnimation");<br />

28 frame.setSize(200, 200);<br />

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

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

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

32 }<br />

33 }<br />

The program displays a running clock, as shown in Figure 16.20. ClockAnimation<br />

creates a StillClock (line 5). Line 11 creates a Timer for a ClockAnimation. The timer<br />

is started in line 12. The timer fires an ActionEvent every second, and the listener responds<br />

<strong>to</strong> set a new time (line 19) and repaint the clock (line 20). The setCurrentTime() method<br />

defined in StillClock sets the current time in the clock.<br />

FIGURE 16.20<br />

A live clock is displayed in the panel.

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

Saved successfully!

Ooh no, something went wrong!