JavaFX将BooleanProperty绑定到Paint

时间:2015-04-16 10:47:50

标签: binding javafx-8

我正在编写一个代码,可以从某些其他代码的一部分中获取一些布尔值,并相应地更改屏幕上某些圆的颜色。但是我试图将布尔值绑定到颜色时遇到了问题。我最终得到了这个:

unit1.getNeuron().getWorkingProperty().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (newValue == Boolean.FALSE) {
                controller.paint1 = new ObservableValueBase<Paint>() {

                    @Override
                    public Paint getValue() {
                        return Color.RED;
                    }
                };
            } else {
                controller.paint1 = new ObservableValueBase<Paint>() {

                    @Override
                    public Paint getValue() {
                        return Color.DODGERBLUE;
                    }
                };

            }
        }
    });
  • 但我必须为我使用的n个变量重复n次。有没有不同的方法来实现这个?

1 个答案:

答案 0 :(得分:4)

让&#39;如果你想根据ObservableObjectValue<Paint>创建一个想要切换的ObservableBooleanValue,那么Bindings就是你的朋友:

final ObservableBooleanValue booleanCondition = unit1.getNeuron().getWorkingProperty();
final ObservableObjectValue<Paint> paintProperty = Bindings.when(booleanCondition).then(Color.RED).otherwise(Color.DODGERBLUE);