我在 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();
}
});
}
}