【问题标题】:Directly update button state JavaFX直接更新按钮状态JavaFX
【发布时间】:2019-10-01 09:31:08
【问题描述】:

我有一个 GUI,一旦按下“上传”按钮,它就会通过串行上传一堆设置。

此上传需要一些时间,并且其中包含一些 Thread.sleep,因此在上传期间 GUI 会冻结,但仍允许用户再按一下上传按钮,这会导致更多冻结。

直接禁用上传按钮、在后台上传并在完成后启用按钮的最佳方法是什么?

【问题讨论】:

    标签: eclipse button javafx


    【解决方案1】:

    感谢您的回复。

    为了回答我自己的问题,我已经通过创建任务找到了一个简单的解决方案:

    public class uploadTask extends Task<String> {
      @Override
      protected String call() throws Exception {
      }
    }
    

    【讨论】:

      【解决方案2】:

      我建议使用RxJavaFx

          import java.util.concurrent.TimeUnit;
      
          import io.reactivex.Observable;
          import io.reactivex.rxjavafx.observables.JavaFxObservable;
          import io.reactivex.rxjavafx.schedulers.JavaFxScheduler;
          import io.reactivex.schedulers.Schedulers;
          import javafx.application.Application;
          import javafx.scene.Scene;
          import javafx.scene.control.Button;
          import javafx.scene.layout.StackPane;
          import javafx.stage.Stage;
      
          public class BackgroundTaskButtonApp extends Application {
      
              public static void main(String[] args) {
                  launch(args);
              }
      
              @Override
              public void start(Stage stage) throws Exception {
                  Button button = new Button("Run!");
                  StackPane stackPane = new StackPane(button);
      
                  Scene scene = new Scene(stackPane, 400, 400);
                  stage.setScene(scene);
                  stage.show();
      
                  JavaFxObservable.actionEventsOf(button)
                  .doOnNext(event -> button.setDisable(true))
                  .switchMap(event -> Observable.just(event).observeOn(Schedulers.single()).doOnNext(e -> runLongTask()))
                  .observeOn(JavaFxScheduler.platform())
                  .doOnNext(event -> button.setDisable(false))
                  .subscribe();
              }
      
              private void runLongTask() {
                  System.out.println(Thread.currentThread().getName() + " runLongTask()");
                  try {
                      TimeUnit.SECONDS.sleep(2);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2019-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多