Java 简易计时器
程序员文章站
2022-05-31 10:49:54
...
Java简易计时器
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.*;
import javax.swing.Timer;
import java.text.*;
public class time extends JFrame implements ActionListener{
Timer time;
JTextField text;
JButton bStart,bStop,bGo;
//SimpleDateFormat m;
long t = 0;
time(){
time= new Timer(1000,this); //timer(int a,object b) time 对象做计时器的监视器;
//m=new SimpleDateFormat("hh:mm:ss"); //设置时钟样式;
text = new JTextField(10);
bStart = new JButton("start");
bStop = new JButton("stop");
bGo =new JButton("go on");
bStart.addActionListener(this);
bStop.addActionListener(this);
bGo.addActionListener(this);
setLayout(new FlowLayout());
add(bStart);
add(bStop);
add(bGo);
add(text);
setSize(500,500);
validate();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==time)
{
t=t+1;
int s=(int)t%60;
int m=(int)t/60%60;
int h=(int)t/3600;
text.setText("时间: "+h+":"+m+":"+s);
}
if(e.getSource()==bStart)
{
time.start();
}
if(e.getSource()==bStop)
{
time.stop();
}
if(e.getSource()==bGo)
{
time.restart();
}
}
}
运行截图