java在窗体中,如何使用timer每秒获取一个系统当前时间
2个回答
展开全部
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;
}
}
}
你试试!
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;
}
}
}
你试试!
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询