在Java框架标题栏上显示运行时间



我正试图让它在实时的frame.setTitle上显示经过的时间,但我很难找到该怎么办,有人能帮我吗?这是我的代码

DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss:aa yyyy/MM/dd");
Calendar cal = Calendar.getInstance();

frame.setTitle("[SESSION] - "+ myUsername +" Elapsed Time " + dateFormat.format(cal.getTime()) );

我想你可以创建一个每秒执行一次的Timer来更新标题(我不确定它的性能如何,但它应该能完成任务(

class UpdateFrame extends TimerTask {
public void run() {
frame.setTitle("[SESSION] - "+ myUsername +" Elapsed Time " + dateFormat.format(cal.getTime()) );
}
}
// And From your main() method or any other method, maybe where you initialize the JFrame
NoiseMap noisemap;
Timer timer = new Timer();
timer.schedule(new UpdateFrame(), 0, 1000);

您还需要传递JFrame对象,可能还有开始计数时的DateFormat或Calendar,我还没有测试过,但它应该可以

class UpdateFrame extends TimerTask {
JFrame frame;
public UpdateFrame(JFrame frame) {
this.frame = frame;
}
public void run() {
frame.setTitle("[SESSION] - "+ myUsername +" Elapsed Time " + dateFormat.format(cal.getTime()) );
}
}
// And From your main() method or any other method, maybe where you initialize the JFrame
NoiseMap noisemap;
Timer timer = new Timer();
timer.schedule(new UpdateFrame(frame), 0, 1000);

最新更新