用java编写一个计数器或计时器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用java编写一个计数器或计时器相关的知识,希望对你有一定的参考价值。
要可以设置计数或计时的时间间隔、实现开始、停止功能,要用到Thread
import java.awt.BorderLayout;import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TimerDemo extends JFrame implements ActionListener
private static final long serialVersionUID = 201306211111L;
private JTextField screen = new JTextField("0");
private JButton start = new JButton("开始");
private JButton reset = new JButton("重置");
private JPanel panel = new JPanel();
private boolean isRunning;
private int time;
private int timeBetween;
public TimerDemo(int timeBetween)
super("计时器");
this.timeBetween = timeBetween;
try
init();
catch (Exception e)
e.printStackTrace();
public TimerDemo()
super("计时器");
this.timeBetween = 100;
try
init();
catch (Exception e)
e.printStackTrace();
private void init()
panel.setLayout(new GridLayout());
panel.add(start);
panel.add(reset);
start.addActionListener(this);
reset.addActionListener(this);
screen.setFont(new Font("幼圆", Font.BOLD, 60));
screen.setHorizontalAlignment(JTextField.CENTER);
screen.setEditable(false);
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.add(panel, BorderLayout.SOUTH);
c.add(screen, BorderLayout.CENTER);
this.setSize(200, 150);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);
public static void main(String[] args)
new TimerDemo(1);// 设定 1ms/次
// new TimerDemo();
@Override
public void actionPerformed(ActionEvent e)
if (e.getSource() == start)
if (start.getText().equals("开始"))
start.setText("暂停");
isRunning = true;
else if (start.getText().equals("暂停"))
start.setText("开始");
isRunning = false;
if (e.getSource() == reset)
start.setText("开始");
screen.setText("0");
isRunning = false;
time = 0;
new Thread(new TimeZone()).start();
class TimeZone implements Runnable
@Override
public void run()
while (isRunning)
time++;
if (time >= Integer.MAX_VALUE)
screen.setText("ERROR");
JOptionPane.showMessageDialog(null, "ERROR");
isRunning = false;
screen.setText(String.valueOf(time));
try
Thread.sleep(timeBetween);
catch (Exception e)
e.printStackTrace();
参考技术A import java.io.IOException;
import java.util.Timer;
public class TimerTest
public static void main(String[] args)
Timer timer = new Timer();
timer.schedule(new MyTask(), 1000, 2000);//在1秒后执行此任务,每次间隔2秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.
while(true)//这个是用来停止此任务的,否则就一直循环执行此任务了
try
int ch = System.in.read();
if(ch-'c'==0)
timer.cancel();//使用这个方法退出任务
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
static class MyTask extends java.util.TimerTask
@Override
public void run()
//你要进行的操作
在java中创建一个计数计时器(仅限秒和毫秒)
【中文标题】在java中创建一个计数计时器(仅限秒和毫秒)【英文标题】:Create a count up timer in java (seconds and milliseconds only) 【发布时间】:2013-05-24 19:43:20 【问题描述】:我正在做一个 java 中的倒计时。我找到了以下示例:Creating a Count Up timer to Break in java,它运行良好。但我想以 “mm:ss:SSS” 格式显示时间,因为我想测量非常小的时间响应。所以,当它达到 1000 毫秒时,就是 1 秒。
我做了一些更改,但我无法以假装的格式显示时间。开始出现的数字应该是秒,而不是毫秒。
如果你有比我所关注的更好的例子,那很好。
编辑:更好,但还不能正常工作。计数太慢(这里的 1 分钟对应 2 实际分钟)。我的代码在这里:
public class Counter extends JFrame
private static final String stop = "Stop";
private static final String start = "Start";
private final ClockListener clock = new ClockListener();
private final Timer timer = new Timer(1, clock);
private final JTextField tf = new JTextField(9);
public Counter()
timer.setInitialDelay(0);
JPanel panel = new JPanel();
tf.setHorizontalAlignment(JTextField.RIGHT);
tf.setEditable(false);
panel.add(tf);
final JToggleButton b = new JToggleButton(start);
b.addItemListener(new ItemListener()
@Override
public void itemStateChanged(ItemEvent e)
if (b.isSelected())
timer.start();
b.setText(stop);
else
timer.stop();
b.setText(start);
);
panel.add(b);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(panel);
this.setTitle("Timer");
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
private class ClockListener implements ActionListener
private int minutes;
private int seconds;
private int milliseconds;
@Override
public void actionPerformed(ActionEvent e)
SimpleDateFormat date = new SimpleDateFormat("mm.ss.SSS");
if (milliseconds == 1000)
milliseconds = 000;
seconds++;
if (seconds == 60)
seconds = 00;
minutes++;
tf.setText(String.valueOf(minutes + ":" + seconds + ":" + milliseconds));
milliseconds++;
public static void main(String[] args)
EventQueue.invokeLater(new Runnable()
@Override
public void run()
Counter clock = new Counter();
clock.start();
);
【问题讨论】:
毫秒是 S 不是 m 【参考方案1】:您正在计算并依赖计时器在 1 毫秒内到期。计时器(实际上是操作系统)不能保证在到期前准确且仅发生 1 毫秒,并且您在到期时运行的代码也需要一些时间。相反,使用计时器来触发刷新。我选择了 53 毫秒,因为它给用户一种毫秒飞逝的模糊感觉,但请注意,在用户单击停止后,计时器最后一次更新 1,它不一定是 53 毫秒的倍数。显示的时间与 Timer 过期次数无关,仅与用户按下开始时记录的开始时间和当前系统时间有关:
public class Counter extends JFrame
private static final String stop = "Stop";
private static final String start = "Start";
private final ClockListener clock = new ClockListener();
private final Timer timer = new Timer(53, clock);
private final JTextField tf = new JTextField(9);
private final SimpleDateFormat date = new SimpleDateFormat("mm.ss.SSS");
private long startTime;
public Counter()
timer.setInitialDelay(0);
JPanel panel = new JPanel();
tf.setHorizontalAlignment(JTextField.RIGHT);
tf.setEditable(false);
panel.add(tf);
final JToggleButton b = new JToggleButton(start);
b.addItemListener(new ItemListener()
@Override
public void itemStateChanged(ItemEvent e)
if (b.isSelected())
startTime = System.currentTimeMillis();
timer.start();
b.setText(stop);
else
updateClock();
startTime = 0;
timer.stop();
b.setText(start);
);
panel.add(b);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(panel);
this.setTitle("Timer");
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
private void updateClock()
Date elapsed = new Date(System.currentTimeMillis() - startTime);
tf.setText(date.format(elapsed));
private class ClockListener implements ActionListener
@Override
public void actionPerformed(ActionEvent e)
updateClock();
public static void main(String[] args)
EventQueue.invokeLater(new Runnable()
@Override
public void run()
Counter clock = new Counter();
);
【讨论】:
另请参阅related approach 稍长的时间。以上是关于用java编写一个计数器或计时器的主要内容,如果未能解决你的问题,请参考以下文章
如何正确计时用 Java Spring MVC 编写的 API?