Change javafx circles color in certain time using multithreads

前端 未结 3 531
情深已故
情深已故 2021-01-27 18:45

I am creating traffic light simulator with javafx that changes colour in every 2 seconds (first red light blinks and remain for 2 seconds) using the concept of multithreading. I

3条回答
  •  再見小時候
    2021-01-27 19:34

    From the javadoc of Thread.join

    Waits for this thread to die.

    This means

    thread1.start();
    thread1.join();
    

    doesn't provide any benefits compared to

    taskOne.run();
    

    since this stops the execution of the method invoking join until the Thread completes.


    It's possible to achieve what you're trying to do in a much more elegant way by using Timeline:

    Timeline timeline = new Timeline(
        new KeyFrame(Duration.ZERO, evt -> {
            circle.setFill(Color.RED);
            circle1.setFill(Color.GREY);
            circle2.setFill(Color.GREY);
        }),
        new KeyFrame(Duration.seconds(2), evt -> {
            // TODO: GUI modifications for second state
        }),
        new KeyFrame(Duration.seconds(4), evt -> {
            // TODO: GUI modifications for third state
        })
    );
    timeline.play();
    

    You may need to adjust the duration for the third KeyFrame. The Duration parameter specifies the time from the beginning of the animation. The EventHandlers are executed on the JavaFX application thread and must not contain long-running code such as Thread.sleep. You may need to add additional KeyFrames.

提交回复
热议问题