2016-09-15 58 views
1

我在刷新標籤時遇到問題。 我有一個這樣的功能:刷新標籤無法正常工作javafx

public void majMontantPaye(Double montantPaye) { 
    System.out.println("montant paye : "+montantPaye); 

    setMontantPaye(this.montantPaye+montantPaye); 

    Platform.runLater(() -> labelMontantPaye.setText(String.format("%.2f", this.montantPaye)+Messages.getMessage("0052"))); 
} 

和我的功能是通過API調用。該API與允許插入硬幣的機器通信。我的功能必須在機器上顯示總和插入。

問題是,當我在機器中同時插入大量硬幣時,我的功能正確地調用每個檢測到的硬幣,因此System.out.println("montant paye : "+montantPaye);正確顯示檢測到的每個硬幣,但標籤「labelMontantPaye」不是刷新到檢測到的每個硬幣。只需完成總金額即可。

我猜UI沒有正確刷新,但我不知道如何正確刷新我的標籤。

請幫忙,對不起,我是法國人。

+1

怎麼叫那個方法?也許在應用程序線程上?此外,Messages.getMessage(「0052」)是一個長時間運行的操作?是否有同步的塊/方法可以阻止此操作,直到某些長時間運行的代碼在不同的線程上執行爲止? – fabian

+0

我的函數在另一個線程中執行。我有一個'if(Platform.isFxApplicationThread()){MainApp.getInstance.mainControllerLgetListeAchatController.majMontantPaye(_resteDu); } else {Platform.runLater(() - > MainApp.getInstance.mainControllerLgetListeAchatController.majMontantPaye(_resteDu);}); }' – Benj

+0

用'runLater'將任務排隊到FXApplicationThread。但是當你有很多「事件」時,你只會看到最後的結果。 (也許以前的短時間)。如果你真的想看到結果,我現在不能給你一個解決方案,因爲沒有'runAndWait'就像SwingUtilities – Clayn

回答

0

您可以遵循以下邏輯:

正如在評論中提到: 使用Platform.runLater(......),你排隊任務到JavaFXThread。但是當你有很多「事件」時,你只會看到最後的結果。 (也許以前的短時間)。

使用BlockingQueue來存儲插入的每個硬幣。使用下面的方法(也可以看看可用方法的教程,這裏我使用的是put,如果插入了最大硬幣,它將阻止當前線程進入隊列,如果你不想要這個設置像500.000最大的東西):

public void insertCoin(//maybe the kind of coin){ 
     //add the coin into the BlockingQueue 
     blockingQueue.put(//coin); 
} 

使用Thread其運行的是無限loop.The線程被喚醒 每次新硬幣被插入,當完成時,線程 個等待JavaFXThread刷新標籤文本:

new Thread(() -> { 

     //Run an infinity Thread 
     while (true) { 

      // Blocks until the queue has really any coins inserted 
      blockingQueue.get(); 

      // Synchronize with javaFX thread 
      CountDownLatch latch = new CountDownLatch(1); 
      Platform.runLater(() -> { 
       label.setText(....); 
       latch.countDown(); 
      }); 

      // Block the Current Thread until the text is refreshed from 
      // JavaFX Thread 
      latch.await(); 

     } 
}).start();