禁用JavaFx中进度栏中的“取消”按钮

时间:2016-08-02 06:41:14

标签: javafx java-8

我在javafx中创建了一个进度条。默认情况下会有取消Button。我只想在任务完成时禁用此取消按钮。

jobProgressView.setGraphicFactory(task -> {
    return new Button("save");
});

1 个答案:

答案 0 :(得分:1)

如果没有更多代码,我只能做出猜测。即使您添加的代码也不足以了解实施中的所有内容。

因此,此解决方案假设您有一个正在运行的任务并在进度条上显示它的进度。这里的任务包含在一个服务中,可以重新启动(也许你还需要这个?)。

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class CancelButtonDemo extends Application {

    Service<Integer> service = new MyService();

    @Override
    public void start(Stage primaryStage) {

        Button start = new Button();
        Button cancel = new Button();
        ProgressBar progress = new ProgressBar(0);

        start.setText("Run Task");
        start.setOnAction((ActionEvent event) -> {
            if (!(service.getState().equals(Worker.State.READY))) {
                service.reset();
            }
            progress.progressProperty().bind(service.progressProperty());
            service.start();
        });
        start.disableProperty().bind(service.runningProperty());

        cancel.setText("Cancel Task");
        cancel.setOnAction((ActionEvent event) -> {
            service.cancel();
            progress.progressProperty().unbind();
            progress.setProgress(0);
        });
        cancel.disableProperty().bind(Bindings.not(service.runningProperty()));

        VBox root = new VBox(20);
        root.setAlignment(Pos.CENTER);
        root.getChildren().addAll(start, progress, cancel);
        Scene scene = new Scene(root, 300, 250);
        primaryStage.setTitle("Cancel Button Demo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    class MyService extends Service<Integer> {

        @Override
        protected Task<Integer> createTask() {
            return new Task<Integer>() {

                @Override
                protected Integer call() throws Exception {
                    int iterations;
                    for (iterations = 0; iterations < 10000000; iterations++) {
                        if (isCancelled()) {
                            updateMessage("Cancelled");
                            break;
                        }
                        updateMessage("Iteration " + iterations);
                        updateProgress(iterations, 10000000);
                    }
                    return iterations;
                }
            };
        }
    }
}

上述应用程序如下所示:

enter image description here

相关问题