If CheckBox is set to true, an inscription should appear temporarily in the HBox. Tried to do so, but if you comment out the last HBox cleanup, it will be seen that the Label is added after the timer has completed. I do not understand why? Can someone tell me how to do it correctly

checkBox.selectedProperty() .addListener((observable, oldValue, newValue) -> { if (newValue) { hbox.getChildren().clear(); hbox.getChildren().add(label); sleep(5000); hbox.getChildren().clear(); } }); private void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } 

I tried this:

  checkBox.selectedProperty() .addListener((observable, oldValue, newValue) -> { if (newValue) { hbox.getChildren().clear(); hbox.getChildren().add(label); sleep(5000); } }); private void sleep(long millis) { Platform.runLater(() -> { Thread thread = new Thread(); try { thread.sleep(millis); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } hbox.getChildren().clear(); }); } 

But: 1) For some reason, this event only works once; 2) If CheckBox is selected again while the event is running, it must be restarted.

  • UI cannot be put to sleep. thereby blocking the processing of any events. launch a separate stream and use Platform.runLater in it to update the UI. - Mikhail Vaysman

1 answer 1

Use the Service for this.

Sample code:

 Service < Void > service = new Service < Void > () { @Override protected Task < Void > createTask() { return new Task < Void > () {@ Override protected Void call() throws Exception { hbox.getChildren().clear(); hbox.getChildren().add(label); Thread.sleep(5000); return null; } }; }}; service.setOnSucceeded(event - > { box.getChildren().remove(label); }); checkBox.selectedProperty().addListener((observable, oldValue, newValue) - > { if (newValue) { service.restart() } }); 
  • In the trailer works, it was necessary only hbox.getChildren (). Clear (); hbox.getChildren (). add (label); wrap in Platform.runLater - hmeli7