2017-03-06 62 views
0

我使用JavaFX工作同步和我解析一個相當大的文件。與UI線程

我在處理解析一類這樣做,和我創建一個新的線程來做到這一點因此,儘管進展不鎖定的用戶界面。

這裏是我的代碼片段:

Thread thread = new Thread(new Runnable() { 
     @Override 
     public void run() { 

     try 
     { 
      // ... Do parsing in here 
     } 
     catch(Exception ex) 
     { 
      // ... Show Exception 
     } 
     } 
    }); 

    thread.start(); 

我的UI是依賴於正被解析(它顯示在UI)的數據。

反正我有可以syncronize這個線程和UI線程,這樣的UI更新的文件被解析?

+1

'Task.updateValue'萬一單個對象有足夠的信息來更新UI。否則'Platform.runLater' ... – fabian

+0

我試過Platform.runLater,但它似乎沒有更新UI。 –

+0

@timbobaggins如果您的代碼無法按照您的方式工作,並且您需要幫助,請在該問題中包含該代碼。 –

回答

0

你可以做這樣的事情。

final int size = //determine the size of the file; 
     Service<Void> service = new Service<Void>() { 
      @Override 
      protected Task<Void> createTask() { 
       return new Task<Void>() { 
        @Override 
        protected Void call() throws Exception { 
         loop while parsing... { 
          Platform.runLater(() -> updateProgress(getWorkDone() + 1, size)); 

         } 
         return null; 
        } 
       }; 
      } 
     }; 

     service.setOnFailed(event -> //error handling); 
     progressIndicator.visibleProperty().bind(service.runningProperty()); 
     progressIndicator.progressProperty().bind(service.progressProperty()); 
     service.start(); 
+0

您不需要在應用程序線程上執行'updateProgress'。在'progress'屬性的修改是在應用程序線程自動完成... – fabian

+0

@fabian沒有runLater()FX抱怨,任務不允許在FX主題進行更新。這很奇怪。稍後添加運行修復了編譯問題。 –

+0

看看的Javadoc:https://docs.oracle.com/javase/8/javafx/api/javafx/concurrent/Task.html#updateProgress-long-long-它包含以下句子:*「這種方法可以安全地從任何線程調用。「*。此外,這肯定不是你使用'javac'得到的編譯錯誤... – fabian