Reputation: 87
I'm making a JavaFX based Connect4 game UI. It is AI based.
I need the AI's disk to drop after the user's disk has dropped down fully on the board. As soon as the user clicks to drop his disk, the user's disk and AI's disk drop at the same time.
I used the ScheduledService class. This allowed to use an initial delay but the task, continues to execute continuously.
I tried to use TimerTask too, but that throws exception when the code tries to modify UI elements.
How do I make a thread that runs after an initial delay of (say 500ms), executes once (modifying UI elements) and then terminates (not executing repeatedly like in ScheduledService class)?
Upvotes: 2
Views: 239
Reputation: 2825
If you want modify gui from not a UI thread you must use:
Platform.runLater
http://docs.oracle.com/javafx/2/api/javafx/application/Platform.html#runLater(java.lang.Runnable)
In order to set a delay, try this:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(() -> {
//do something
Platform.runLater(() -> {
//do something with ui
});
}, 5, TimeUnit.SECONDS);
Upvotes: 2