当前位置: 技术问答>java相关
怎样定时触发一事件,请教
来源: 互联网 发布时间:2015-11-15
本文导语: 我想每隔一段时间,做一件事, 怎样实现 有现成的定时器么。 还是要自己做一个Listener | import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TimeTest implements ActionListener { private int seconds = 1; pu...
我想每隔一段时间,做一件事,
怎样实现
有现成的定时器么。
还是要自己做一个Listener
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TimeTest implements ActionListener
{
private int seconds = 1;
public TimeTest()
{
Timer oneSecondTimer = new Timer(1000,this);
Timer timerWithInitialDelay = new Timer(2000,new TimerWithDelayListener());
Timer oneTimeTimer = new Timer(10000,new OneTimeListener());
timerWithInitialDelay.setInitialDelay(5000);
oneTimeTimer.setRepeats(false);
oneSecondTimer.start();
timerWithInitialDelay.start();
oneTimeTimer.start();
}
public void actionPerformed(ActionEvent e)
{
if(seconds == 0)
System.out.println("Time:" + seconds + " second");
else
System.out.println("Time:" + seconds + " seconds");
seconds++;
}
public static void main(String[] args)
{
new TimeTest();
while(true);
}
}
class TimerWithDelayListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Timer whit Delay Ringing");
}
}
class OneTimeListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("One Time Timer Ringing");
}
}
import java.awt.event.*;
import javax.swing.*;
public class TimeTest implements ActionListener
{
private int seconds = 1;
public TimeTest()
{
Timer oneSecondTimer = new Timer(1000,this);
Timer timerWithInitialDelay = new Timer(2000,new TimerWithDelayListener());
Timer oneTimeTimer = new Timer(10000,new OneTimeListener());
timerWithInitialDelay.setInitialDelay(5000);
oneTimeTimer.setRepeats(false);
oneSecondTimer.start();
timerWithInitialDelay.start();
oneTimeTimer.start();
}
public void actionPerformed(ActionEvent e)
{
if(seconds == 0)
System.out.println("Time:" + seconds + " second");
else
System.out.println("Time:" + seconds + " seconds");
seconds++;
}
public static void main(String[] args)
{
new TimeTest();
while(true);
}
}
class TimerWithDelayListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Timer whit Delay Ringing");
}
}
class OneTimeListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("One Time Timer Ringing");
}
}