1.首先写一个java监听器的类,实现ActionListener接口
package com.test;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import com.model.TimePrinter;
public class DingshiqiTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//新建一个监听器
ActionListener tp=new TimePrinter();
//构造一个定时器 每隔一秒钟通告tp一次,其中第一个参数的单位是毫秒 1秒=1000毫秒
Timer t=new Timer(1000,tp);
//启动定时器 一旦启动成功,定时器timer将会调用TimePrinter 的actionPerformed方法
//与之对应的结束的方法为stop()
t.start();
//java自带的显示一个对话框 用于退出当前程序的
JOptionPane.showMessageDialog(null, "quit?");
System.exit(0);
}
}
2.然后编写测试类
package com.model;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
public class TimePrinter implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
//获取当前时间
Date now=new Date();
//打印当前时间
System.out.println("At the stone,the time is "+now);
//使用工具箱里面默认的工具包 获取到“叮”的一声提醒
Toolkit.getDefaultToolkit().beep();
}
}