Timers in Java Swing
A Swing timer (an instance of javax.swing.Timer) fires one or more action events
after a specified delay. Don't confuse Swing timers with the general-purpose
timer facility that was added to the java.util package in release 1.3. This page
describes only Swing timers.
In general, we recommend using Swing timers rather than
general-purpose timers for GUI-related tasks because Swing timers all share the
same, pre-existing timer thread and the GUI-related task automatically executes
on the event-dispatch thread. However, you might use a general-purpose timer if
you don't plan on touching the GUI from the timer, or need to perform lengthy
processing.
You
can use Swing timers in two ways:
To perform a task once, after a delay.For example, the tool
tip manager uses Swing timers to determine when to show a tool tip and when to
hide it.
To perform a task repeatedly.For example, you might perform
animation or update a component that displays progress toward a goal.
Swing timers are very easy to use. When you create the
timer, you specify an action listener to be notified when the timer "goes
off". The actionPerformed method in this listener should
contain the code for whatever task you need to be performed. When you create
the timer, you also specify the number of milliseconds between timer firings.
If you want the timer to go off only once, you can invoke setRepeats(false) on the timer. To start the timer,
call its start method. To suspend it, call stop.
timer =
new Timer(speed, this);
timer.setInitialDelay(pause);
timer.start();
import javax.swing.*;
import java.awt.event.*;
import java.awt.Graphics;
import java.util.Date;
import java.awt.Font;
import java.awt.Color;
public class TimerEx extends
JFrame implements ActionListener
{ Timer t;
JLabel l=new JLabel(" ",JLabel.CENTER);
public TimerEx()
{
t=new Timer(1000,this);
l.setOpaque(true);
l.setBackground(new Color(100,50,50));
l.setFont(new
Font("Arial",Font.BOLD,60));
l.setForeground(Color.yellow);
getContentPane().add(l);
t.start();
setSize(400,200);
setVisible(true);
setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent ae){
Date d=new Date();
String
s=(d.getHours()-12)+":"+d.getMinutes()+":"+d.getSeconds();
l.setText(s);
}
public static void main(String ag[])
{ TimerEx te=new TimerEx();
}
}






0 comments:
Post a Comment