/** * 测试swing中Timer的使用 * 一个显示时间的GUI程序 * @author wasw100 * */ public class TimerTest extends JFrame implements ActionListener { // 一个显示时间的JLabel private JLabel jlTime = new JLabel(); private Timer timer;
public TimerTest() { setTitle("Timer测试"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(180,80); add(jlTime);
//设置Timer定时器,并启动 timer = new Timer(500,this); timer.start(); setVisible(true); }
/** * 执行Timer要执行的部分, */ @Override public void actionPerformed(ActionEvent e) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); jlTime.setText(format.format(date));
}
public static void main(String[] args) { new TimerTest(); } }程序说明:类实现了ActionListener接口,所以可以直接timer = new Timer (500,this);使用this初始化计时器。当计时器启动后(timer.start()执行后),每隔500毫秒执行一次实现的 ActionListener 接口中的actionPerformed的方法体这里在补充一点显示时间格式的知识:DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");MM表示月份 mm表示分钟 hh:12小时制显示几点 HH:24小时制显示几 点