您的位置:首页 > 其它

内部类实现定时器的例子

2015-07-31 10:15 405 查看
代码如下:

package com.corejava.test;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.JOptionPane;
import javax.swing.Timer;

public class InnerClassTest {
public static void main(String[] args) {
TalkingClock clock = new TalkingClock(1000, true);
clock.start();

JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}

class TalkingClock {
private int interval;
private boolean beep;

public TalkingClock(int interval, boolean beep) {
super();
this.interval = interval;
this.beep = beep;
}

public void start() {
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval, listener);
t.start();
}

public class TimePrinter implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {
Date now = new Date();
System.out.println("At the tone,the time is " + now);
if (beep)
Toolkit.getDefaultToolkit().beep();
}

}
}


实现结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: