2015-09-09 100 views
0

我想有效地對JavaFX TableView進行「輪詢」,以便如果另一個用戶在數據庫中創建一個作業,當前用戶會選擇它(比如說每隔5秒)。定期刷新JavaFX TableView

我試過使用Timer;

new Timer().schedule(new TimerTask() { 
    @Override 
    public void run() { 
     try { 
      newI(connection, finalQuery, adminID); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
    } 
}, 0, 5000); 

然而這得到了以下錯誤:Exception in thread "Timer-0" java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = Timer-0我假設意味着它不是在JavaFX的支持?我如何能夠定期更新JavaFX中的TableView?

+0

這並不意味着它不是在JavaFX的支持。這意味着您正在從後臺線程更新某些內容,而不是從FX應用程序線程中更新。考慮使用['ScheduledService'](http://docs.oracle.com/javase/8/javafx/api/javafx/concurrent/ScheduledService.html)而不是定時器,並閱讀多線程和JavaFX(例如http ://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm#JFXIP546或http://stackoverflow.com/questions/30249493/using-threads-to-make-database-requests或many其他來源) –

回答

3

可以使用ScehduleService-這樣的事情...

private class MyTimerService extends ScheduledService<Collection<MyDTO>> { 
    @Override 
    protected Task<Collection<MyDTO>> createTask() { 
     return new Task<Collection<MyDTO>>() { 
      @Override 
      protected Collection<MyDTO> call() throws ClientProtocolException, IOException { 
        //Do your work here to build the collection (or what ever DTO). 
       return yourCollection; 
      } 
     }; 
    } 
} 

    //Instead of time in your code above, set up your schedule and repeat period.  
    service = new MyTimerService() ; 
    //How long the repeat is 
    service.setPeriod(Duration.seconds(5)); 
    //How long the initial wait is 
    service.setDelay(Duration.seconds(5)); 

    service.setOnSucceeded(event -> Platform.runLater(() -> { 
     //where items are the details in your table 
     items =  service.getValue(); 
    })); 

    //start the service 
    service.start(); 
+0

儘管您可能想用真實的返回類型替換'Void',並讓'call'方法返回數據庫查詢的結果(例如'List ')。 –

+0

謝謝James_D - 在我的使用案例中,我沒有回報.... :)我將編輯.. –

+0

@James_D你知道爲什麼會發生這種情況嗎? https://stackoverflow.com/questions/44152630/javafx-random-white-empty-pages-issue-in-tableview-while-pagination –