Java Reference
In-Depth Information
8.7.2
javax.swing.Timer
Although it has fewer options, the
javax.swing.Timer
can do some of the
same basic timing tasks as
java.util.Timer
. Below we show another version
of the digital clock except that it uses
javax.swing.Timer
. This timer con-
tacts an
ActionListener
after every time period rather than a
TimerTask
object. Here the applet implements the
ActionListener
interface. The con-
structor for the timer takes as arguments the update period value and the reference
to the applet. The timer is then started and after every second the
actionPer-
formed()
method will be invoked and the clock panel repainted. The applet's
stop()
method stops the timer.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
/** This applet implements Runnable and uses a thread
*tocreate a digital clock. **/
public class
ClockTimer2
extends JApplet
implements ActionListener
{
javax.swing.Timer fTimer;
// Need panel reference in run().
DateFormatPanel fClockPanel;
public void init ()
{
Container content
-
pane
=
getContentPane ();
// Create an instance of DrawingPanel
fClockPanel
=
new DateFormatPanel ();
// Add the DrawingPanel to the contentPane.
content
-
pane.add (fClockPanel);
}
public void start () {
// Send events very 1000ms.
fTimer = new javax.swing.Timer (1000, this);
// Then start the timer.
fTimer.start ();
}
Search WWH ::
Custom Search