Search code examples
javamultithreadingjavafxexitplatform

How to properly exit javaFX Platform.runLater


The code below doest not exit properly when I close the application. I believe the issue is where do i exactly call the system.exit and platform.exit....

hour_Label.textProperty().bind(hour);
minute_Label.textProperty().bind(minute);
second_Label.textProperty().bind(second);

new Thread(() -> 
{    
    for (;;) 
    {                 
        try 
        { 
            final SimpleDateFormat simpledate_hour = new SimpleDateFormat("h");
            final SimpleDateFormat simpledate_minute = new SimpleDateFormat("mm");
            final SimpleDateFormat simpledate_second = new SimpleDateFormat("s");
            Platform.runLater(new Runnable() {
                @Override public void run() 
                {
                    hour.set(simpledate_hour.format(new Date()));
                    minute.set(simpledate_minute.format(new Date()));
                    second.set(simpledate_second.format(new Date())); 
                }
            });
            Thread.sleep(200);                
        }
        catch (Exception e){logger.warn("Unexpected error", e); Thread.currentThread().interrupt(); Platform.exit(); System.exit(0);}
    }
}).start();

Solution

  • Don't use threads! Use a Timeline instead:

    Timeline clock = new Timeline(
        new KeyFrame(Duration.seconds(0), evt -> {
            LocalTime now = LocalTime.now();
            hour.set(String.format("%d", now.getHour()));            
            minute.set(String.format("%02d", now.getMinute()));            
            second.set(String.format("%d", now.getSecond()));            
        }),
        new KeyFrame(Duration.seconds(1))
    );
    clock.setCycleCount(Animation.INDEFINITE);
    clock.play();
    

    As a Timeline is run by the FX Application Thread, you don't need any synchronization via Platform.runLater(...). Apart from that, you can start and stop the timeline as desired, and it automatically terminates when the FX Application Thread stops.