定期刷新JavaFX TableView

时间:2015-09-09 13:53:22

标签: java javafx tableview

我想有效地"民意调查"在JavaFX TableView上,如果另一个用户在数据库中创建了一个作业,那么当前用户就会选择它(让我们每5秒钟一次)。

我尝试过使用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?

1 个答案:

答案 0 :(得分: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();