可恢复的财产不能正常工作

时间:2015-08-10 04:38:24

标签: java javafx

所以我创建了一个类RevertableDoubleProperty,目标是每次更改,以便与用户确认更改。如果true,则还原更改。问题是,我不能简单地忽略更改,因为此属性绑定(双向)到微调器值,因此忽略更改不会修复微调器。我需要一种方法告诉微调器重置。

注意这里的抽象,我不能只是将微调器实例传递给属性并以这种方式重置它,我需要从RevertableDoubleProperty内部获取对微调器值属性的引用。

这引起了我好几周的问题,所以任何帮助都会非常感谢!

public class Test extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        Property doubleProperty = new RevertableDoubleProperty();
        doubleProperty.setValue(5);
        ((RevertableDoubleProperty)doubleProperty).setOnPropertyChange(new Callback<Void, Boolean>() {
            @Override
            public Boolean call(Void aVoid) {
                final Alert confirm = new Alert(Alert.AlertType.CONFIRMATION);
                confirm.setContentText("Are you sure you want to do that?");
                final ButtonType responce = confirm.showAndWait().get();
                assert responce == ButtonType.CANCEL || responce == ButtonType.CLOSE || responce == ButtonType.OK;
                if (responce == ButtonType.CANCEL || responce == ButtonType.CLOSE) {
                    return true;
                }
                return false;
            }
        });
        Spinner<Double> spinner = new Spinner<Double>(0.0, 100.0, 1.0, 1.0);
        spinner.getValueFactory().valueProperty().bindBidirectional(doubleProperty);

        Label label = new Label();
        Bindings.bindBidirectional(label.textProperty(), ((Property)spinner.valueProperty()), new NumberStringConverter());

        FlowPane flowPane = new FlowPane();
        flowPane.getChildren().addAll(spinner, label);
        primaryStage.setScene(new Scene(flowPane));
        primaryStage.show();
    }

    class RevertableDoubleProperty extends SimpleDoubleProperty {
        private DoubleProperty proxyDoubleProperty;
        private Callback<Void, Boolean> onPropertyChange;

        @Override
        public void set(double value) {
            if (onPropertyChange != null && onPropertyChange.call(null)) {//The call returns true if the change wants to be reverted
                //What to do here?
                return;
            }
            if (proxyDoubleProperty == null) {
                proxyDoubleProperty = new SimpleDoubleProperty();
            }
            System.out.println("setting");
            proxyDoubleProperty.set(value);
            super.set(value);
        }

        public void addListener(ChangeListener changeListener) {
            System.out.println("Added listener");
            proxyDoubleProperty.addListener(changeListener);
        }
        public void setOnPropertyChange(Callback<Void, Boolean> onPropertyChange) {
            this.onPropertyChange = onPropertyChange;
        }
    }
}

0 个答案:

没有答案