我正在制作一个秒表,我知道如何做所有事情,除了找出我的计时器对象已经运行了多长时间。有没有像 timer.getElapsedTime()
这样的方法或者类似的东西?
编辑:有数字表示 00 00 00。每秒都需要递增。我的思考过程是seconds = timer.getElapsedTime();
secs.setText(seconds)
最佳答案
只需在设置计时器时将 System.currentTimeMillis() 保存在某个变量中,并在需要耗时时将该值与当前返回值进行比较。
编辑:让计时器每秒触发一次。请注意,我们每次触发时都会重新设置计时器,以防止滞后和处理时间累积。
package timertest;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class TimerTest implements ActionListener {
JLabel timeDisplay;
long startTime;
Timer timer;
int seconds;
public void createAndShowGUI() {
JFrame frame=new JFrame("Stopwatch");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timeDisplay=new JLabel("0");
frame.getContentPane().add(timeDisplay);
frame.pack();
frame.setVisible(true);
startTime=System.currentTimeMillis();
seconds=1;
timer=new Timer(1000, this);
timer.setRepeats(false);
timer.start();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TimerTest().createAndShowGUI();
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
long now=System.currentTimeMillis();
long elapsed=now-startTime;
seconds++;
timeDisplay.setText(elapsed+" Milliseconds since start");
timer.setInitialDelay((int)(startTime+seconds*1000-now));
timer.start();
}
}
关于java - 查找 Swing 计时器已经运行了多长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22025534/