jbanks
jbanks

Reputation: 193

Periodically Refresh JavaFX TableView

I'd like to effectively "poll" on a JavaFX TableView so that if a job is created in the database by another user the current user would pick it up (let's say every 5 seconds).

I have tried using Timer;

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

However this gets the following error: Exception in thread "Timer-0" java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = Timer-0 which I assume means that it is not supported in JavaFX? How am I able to periodically update the TableView in JavaFX?

Upvotes: 0

Views: 1650

Answers (1)

purring pigeon
purring pigeon

Reputation: 4209

You can use a ScehduleService- something like this...

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();

Upvotes: 3

Related Questions