CodeWriter CodeWriter - 4 months ago 28
Java Question

How to make a delayed thread that runs only once modifying some UI elements in JavaFX?

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)?


If you want modify gui from not a UI thread you must use:


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