與許多面向對象的編程一樣,java也有Timer類,用來計算時間。它在java.swt中。
通過使用Timer可以動態的顯示時間
Timer的實現
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Date;
public class mainFrame extends JFrame implements ActionListener {
private JButton stb,pab,reb;
private JPanel pan;
private JTextField text;
Timer time;
public mainFrame(String s){
super (s);
setSize(300,100);
setLocationRelativeTo(null);
pan=new JPanel();
this.setContentPane(pan);
stb=new JButton("開始");
pab=new JButton("停止");
reb=new JButton("重新開始");
pan.add(stb); //將按鈕加入到面板中
pan.add(pab);
pan.add(reb);
stb.addActionListener(this); //加入相關的監聽
reb.addActionListener(this);
pab.addActionListener(this);
text=new JTextField ("時間:**:**:**");
pan.add(text);
time=new Timer(1000,this);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){ //重寫actionPerformed類來實現事件處理
if (e.getSource()==time){
Date d=new Date();
String s=d.toString().substring(11,19);
text.setText("時間:"+s);
}
else if (e.getSource()==stb){
time.start();
}
else if (e.getSource()==pab){
time.stop();
}
else if (e.getSource()==reb){
time.restart();
}
}
}
通過mainFrame類來新建一個窗體,並對按鈕事件進行處理。通過time=new Timer(1000,this)來實例化Timer,並且讓它每隔1000ms觸發一次actionPerformed事件,從而動態的顯示時間。
public class text {
public static void main(String[] args) {
// TODO Auto-generated method stub
mainFrame mf =new mainFrame("我能算時間"); //實例mainFrame來查看效果
}
}