JavaFX periodic background task

后端 未结 5 954
时光说笑
时光说笑 2020-11-21 04:43

I try to run in JavaFX application background thread periodically, which modifies some GUI property.

I think I know how to use Task and Service

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 05:22

    You can use ScheduledService too. I am using this alternative after noticing that during the use of Timeline and PauseTransition occurred some UI freezes in my application, especially when the user interacts with the elements of a MenuBar (on JavaFX 12). Using the ScheduledService these problems no longer occurred.

    class UpdateLabel extends ScheduledService {
    
       private Label label;
    
       public UpdateLabel(Label label){
          this.label = label;
       }
    
       @Override
       protected Task createTask(){
          return new Task(){
             @Override
             protected Void call(){
               Platform.runLater(() -> {
                  /* Modify you GUI properties... */
                  label.setText(new Random().toString());
               });
               return null;
             }
          }
       }
    }
    

    And then, use it:

    class WindowController implements Initializable {
    
       private @FXML Label randomNumber;
    
       @Override
       public void initialize(URL u, ResourceBundle res){
          var service = new UpdateLabel(randomNumber);
          service.setPeriod(Duration.seconds(2)); // The interval between executions.
          service.play()
       }
    }
    

提交回复
热议问题