如何将Java ChangeListener添加到方法返回

时间:2017-12-28 20:07:15

标签: java properties javafx-8 changelistener

我有一个任务控制GUI,其中有一个' Abort'按钮调用一些取消代码(工作正常)。但是,我想将按钮的禁用状态同步到任务是否正在运行,因此如果任务未运行,则禁用该选项。我可以通过它的Boolean Future.isDone()方法检查任务的状态,但是我想让JavaFX通过绑定属性自动管理状态。但是,我无法弄清楚如何建立绑定,或者在方法上设置ChangeListener。任何人都可以建议如何最好地完成?

修改:我认为这个问题最终会提炼到"如何将Future.isDone()包装成一个Observable?"

非常感谢指导。

2 个答案:

答案 0 :(得分:1)

使用Task。您可以观察state属性来修改Button的已禁用属性:

private ExecutorService service;

@Override
public void stop() throws Exception {
    service.shutdownNow();
}

@Override
public void init() throws Exception {
    service = Executors.newSingleThreadScheduledExecutor();
    // service = new ThreadPoolExecutor(1, 2, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
}

@Override
public void start(Stage primaryStage) {
    Button startButton = new Button("Start");

    Task<Void> task = new Task<Void>() {

        @Override
        protected Void call() throws Exception {
            Thread.sleep(5000);
            System.out.println("task finished");
            return null;
        }

    };

    Button cancelButton = new Button("cancel");
    cancelButton.setOnAction(evt -> task.cancel());
    cancelButton.setDisable(true); // button disabled before submitting task

    startButton.setOnAction((ActionEvent event) -> {
        startButton.setDisable(true);

        // cancel Button enabled until task is succeeded/failed/was cancelled
        cancelButton.disableProperty().bind(Bindings.createBooleanBinding(() -> {
            switch (task.getState()) {
                case CANCELLED:
                case FAILED:
                case SUCCEEDED:
                    return true;
                default:
                    return false;
            }
        }, task.stateProperty()));

        // simulate some work to be done by the service
        service.submit(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException ex) {
            }
            System.out.println("runnable finished");
        });
        service.submit(task);
    });

    // show state as text
    Text text = new Text();
    text.textProperty().bind(task.stateProperty().asString());

    VBox root = new VBox(10, startButton, cancelButton, text);

    Scene scene = new Scene(root, 300, 300);

    primaryStage.setScene(scene);
    primaryStage.show();
}

答案 1 :(得分:0)

解决了,或者说足够好。 GUI控件绑定到SimpleBooleanProperty。构造函数启动后台线程Runnable,它在无限循环中轮询isDone()并进行半秒睡眠并更新绑定的SBP。再次感谢fabian,为我指出一个适当的解决方案,以备将来参考。