这应该显示时间,但是当我运行代码时,我得到代码执行的时间。如何让它每秒显示当前时间?
private void Timer(java.awt.event.WindowEvent evt) {
DateFormat timeFormat = new SimpleDateFormat ("HH:mm:ss");
Calendar cali = Calendar.getInstance();
cali.getTime();
String time = timeFormat.format(cali.getTimeInMillis()) ;
System.out.println( timeFormat.format(cali.getTimeInMillis()) );
jLabel4.setText(time);
}
答案 0 :(得分:2)
而不是使用线程并不断使用invokeLater返回到Swing线程,这是少数几个Swing Timer是个好主意的情况之一。
Swing Timer已经回调事件调度线程,因此您可以直接从回调中更新标签。
http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
答案 1 :(得分:2)
参考Ankur的代码
Timer timer = new Timer("Display Timer");
TimerTask task = new TimerTask() {
@Override
public void run() {
// Task to be executed every second
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Calendar cali = Calendar.getInstance();
cali.getTime();
String time = timeFormat.format(cali.getTimeInMillis());
System.out.println(timeFormat.format(cali.getTimeInMillis()));
jLabel4.setText(time);
}
});
} catch (InvocationTargetException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
// This will invoke the timer every second
timer.scheduleAtFixedRate(task, 1000, 1000);
OR 使用The Swing Timer
答案 2 :(得分:1)
使用线程
new Thread(new Runnable
{
public void run()
{
long start = System.currentTimeMillis();
while (true)
{
long time = System.currentTimeMillis() - start;
int seconds = time / 1000;
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
label.setText("Time Passed: " + seconds);
}
});
try { Thread.sleep(100); } catch(Exception e) {}
}
}
}).start();
答案 3 :(得分:1)
试试这个:
Timer timer = new Timer("Display Timer");
TimerTask task = new TimerTask() {
@Override
public void run() {
// Task to be executed every second
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Calendar cali = Calendar.getInstance();
cali.getTime();
String time = timeFormat.format(cali.getTimeInMillis());
System.out.println(timeFormat.format(cali.getTimeInMillis()));
jLabel4.setText(time);
}
};
// This will invoke the timer every second
timer.scheduleAtFixedRate(task, 1000, 1000);