1. Java提供了一个很方便的Timer类,该类在javax.swing,在某些操作需要周期性地执行那么就可以使用计时器。我们可以使用Timer方法的构造方法Time(int a,Object b)来创建一个计时器
当我们使用Timer(int a, Object b)创建计时器,那么对象b就自然成了计时器的监视器,不必像其他的组件一样使用特定的方法来获得监视器,但负责创建监视器的类必须实现ActionListener
2. 下面是具体的代码:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.Timer;
public class WindowTime extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JTextField text;
Timer time;
JButton bStart, bStop, bContinue;
SimpleDateFormat m;
int n = 0;
int start = 1;
public WindowTime() {
time = new Timer(1000, this);
m = new SimpleDateFormat("hh:mm:ss");
text = new JTextField(10);
bStart = new JButton("开始");
bStop = new JButton("暂停");
bContinue = new JButton("继续");
bStart.addActionListener(this);
bStop.addActionListener(this);
bContinue.addActionListener(this);
setLayout(new FlowLayout());
//往容器中假如组件
add(bStart);
add(bContinue);
add(bStop);
add(text);
setSize(500, 500);
validate();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == time){
Date date = new Date();
text.setText("时间: " + m.format(date));
}
else if(e.getSource() == bStart){
time.start();
}
else if(e.getSource() == bStop){
time.stop();
}
else if(e.getSource() == bContinue){
time.restart();
}
}
public static void main(String[] args) {
//运行整个窗口程序只需要新建一个对象即可
@SuppressWarnings("unused")
WindowTime time = new WindowTime();
}
}