2016-07-25 256 views
1

你好,我想問一下關於這個問題的任何建議。JavaFX每秒顯示時間和刷新

我想在標籤或任何對它有利的組件中以HH:MM:SS格式顯示當前時間(每秒刷新一次)。

有什麼建議嗎?

編輯:有人問了一個代碼..所以我把它放在這裏,以更好地描述問題。 「我當時沒有代碼我想要實現的是簡單的GUI日記,並且在其中一個標籤中,我希望顯示剩餘的時間,直到最接近的事件,以及我希望顯示的其他標籤,如時鐘,刷新每個時鐘第二,我需要它來獲得剩餘的工作時間,我所能想到的就是創建新的線程來完成它並刷新時鐘,但是我並不是那種高級的在JavaFX中使用多線程的人,所以我想知道是否有人可以給我建議與東西比多線程那麼複雜(我不知道如何實現線程進入JavaFX組件)」

+0

你能告訴我你的代碼。所以我可以看到任何更正。 –

+0

https://stackoverflow.com/questions/42383857/javafx-live-time-and-date/42384436#42384436 –

回答

0

要使用定時器解決你的任務,你需要實現TimerTask與您的代碼,並使用Timer#scheduleAtFixedRate方法反覆運行代碼:

Timer timer = new Timer(); 
timer.scheduleAtFixedRate(new TimerTask() { 
    @Override 
    public void run() { 
     System.out.print("I would be called every 2 seconds"); 
    } 
}, 0, 2000); 

還要注意,調用任何UI操作必須Swing的UI線程(或FX UI線程,如果你正在使用JavaFX)來完成:

private int i = 0; 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
    Timer timer = new Timer(); 
    timer.scheduleAtFixedRate(new TimerTask() { 
     @Override 
     public void run() { 
      SwingUtilities.invokeLater(new Runnable() { 
       @Override 
       public void run() { 
        jTextField1.setText(Integer.toString(i++)); 
       } 
      }); 
     } 
    }, 0, 2000); 
} 

在JavaFX的情況下,你需要在「FX更新外匯管制UI線程「而不​​是Swing之一。爲了實現這一目標使用javafx.application.Platform#runLater方法,而不是SwingUtilities的

+0

謝謝,但這是多線程,我真的不知道如何在JavaFX GUI中實現它.. – MaraSimo

+0

你也可以檢查這個問題http://stackoverflow.com/questions/34801227/fast-counting-timer-in-javafx –

+1

您正在從AWT事件調度線程更改JavaFX標籤的文本。這違反了JavaFX線程規則,並可能會拋出'IllegalStateException'。 –

4

版本與時間軸:

long endTime = ...; 
Label timeLabel = new Label(); 
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); 
final Timeline timeline = new Timeline(
    new KeyFrame(
     Duration.millis(500), 
     event -> { 
      final long diff = endTime - System.currentTimeMillis(); 
      if (diff < 0) { 
      // timeLabel.setText("00:00:00"); 
       timeLabel.setText(timeFormat.format(0)); 
      } else { 
       timeLabel.setText(timeFormat.format(diff)); 
      } 
     } 
    ) 
); 
timeline.setCycleCount(Animation.INDEFINITE); 
timeline.play(); 
+0

幫助了我。不過,我會使用'LocalDateTime.now()'來代替當前的日期和時間 – Lulero