1

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

CodeWriter
  • 77
  • 1
  • 10
  • possible duplicate of [Java FX modifying UI component state with/without using Platform.runLater](http://stackoverflow.com/questions/26012421/java-fx-modifying-ui-component-state-with-without-using-platform-runlater/26013749#26013749) – ItachiUchiha Mar 22 '15 at 18:56
  • how do I set the initial delay for the thread? I need the Task to execute only once after some specified delay unlike in ScheduledService class that executes the Task repeatedly. – CodeWriter Mar 22 '15 at 19:01
  • You set the [delay in the ScheduledService](http://docs.oracle.com/javase/8/javafx/api/javafx/concurrent/ScheduledService.html#setDelay-javafx.util.Duration-) and on `setOnSucceeded` just `cancel` it. But this too much for a simple job. Just let you new Task sleep for `500ms` before starting execution using `Thread.sleep(500)` inside the `call()` – ItachiUchiha Mar 22 '15 at 19:19
  • A [PauseTransition](http://docs.oracle.com/javase/8/javafx/api/javafx/animation/PauseTransition.html) might be a preferred solution here rather than using multiple threads. – jewelsea Mar 23 '15 at 18:28

1 Answers1

1

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);
Damien
  • 1,161
  • 2
  • 19
  • 31
Aleksander Mielczarek
  • 2,787
  • 1
  • 24
  • 43