我是一名 Java 初学者,我正在尝试构建一个简单的秒表程序,在 swing GUI 上显示时间。制作秒表很容易,但是我找不到让 GUI 每秒更新一次并在秒表上显示当前时间的方法。我该怎么做?
最佳答案
按照这些思路应该可以做到这一点:
import java.awt.EventQueue;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
/** @see https://stackoverflow.com/a/11058263/230513 */
public class Clock {
private Timer timer = new Timer();
private JLabel timeLabel = new JLabel(" ", JLabel.CENTER);
public Clock() {
JFrame f = new JFrame("Seconds");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(timeLabel);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
timer.schedule(new UpdateUITask(), 0, 1000);
}
private class UpdateUITask extends TimerTask {
int nSeconds = 0;
@Override
public void run() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
timeLabel.setText(String.valueOf(nSeconds++));
}
});
}
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final Clock clock = new Clock();
}
});
}
}
timeLabel
将始终显示计时器已运行的秒数。
关于每秒更新 GUI 的 Java 秒表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11058172/