java在窗体中,如何使用timer每秒获取一个系统当前时间

如题所述

第1个回答  2011-01-19
package test1;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class test1_5 extends JFrame implements Runnable,ActionListener{
JTextField tf1=new JTextField(12);
JButton b1=new JButton("开始计时");
JButton b2=new JButton("暂停计时");
int a=0;
public test1_5(){
this.setTitle("计时器");
this.setSize(400, 100);
this.setLayout(new FlowLayout());
this.setResizable(false);
this.add(tf1);
this.add(b1);
this.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
Thread th=new Thread(this);
th.start();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Timestamp time = new java.sql.Timestamp(new java.util.Date().getTime());
Thread.sleep(1000);
if(a==1){
tf1.setText(String.valueOf(time.getHours())+":"+String.valueOf(time.getMinutes()+":"+String.valueOf(time.getSeconds())));
}
else{
tf1.setText("");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
test1_5 tx=new test1_5();
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
JButton b=(JButton)arg0.getSource();
if(b.getText()=="开始计时"){
a=1;
}
else if(b.getText()=="暂停计时"){
a=0;
}
}
}

你试试!本回答被提问者采纳
第2个回答  2011-01-19
利用多线程技术!使用sleep()方法,让线程中断一秒 具体使用方法请查阅java api 中 Runnable
相似回答