假设我有一个ObservableSet<Integer>
整数。我想绘制一个形状,或更具体地说是一个圆形。
Circle circle = new Circle(5);
circle.setFill(Color.RED);
是否可以将这种形状的
visibleProperty()
绑定到JavaFX和JDK8集合中值的存在?例如,如果set包含
5
,则将形状的可见性设置为true
,否则将其设置为false
。通常,是否有任何方法可以绑定到集合内部元素的存在? 最佳答案
看起来似乎没有开箱即用的东西(至少我找不到任何东西),所以我们必须自己做。基本上有两个选择:
将SetChangeListener注册到ObservableSet,在通知时手动更新BooleanProperty
将ObservableSet包裹到SetProperty中,并创建一个BooleanBinding,在接收到任何更改时查询Callable
两者都显得笨拙,可能会有更好的方法。两者的示例:
public class SetContainsBinding extends Application {
private Parent createContent() {
ObservableSet<Integer> numberSet = FXCollections.observableSet(1, 2, 3, 4);
BooleanProperty contained = new SimpleBooleanProperty(this, "contained", true);
int number = 2;
numberSet.addListener((SetChangeListener<Integer>) c -> {
contained.set(c.getSet().contains(number));
});
Circle circle = new Circle(50);
circle.setFill(Color.RED);
circle.visibleProperty().bind(contained);
SetProperty<Integer> setProperty = new SimpleSetProperty<>(numberSet);
BooleanBinding setBinding =
Bindings.createBooleanBinding(() -> setProperty.contains(number), setProperty);
Circle bindingC = new Circle(50);
bindingC.setFill(Color.BLUEVIOLET);
bindingC.visibleProperty().bind(setBinding);
HBox circles = new HBox(10, circle, bindingC);
Button remove = new Button("remove");
remove.setOnAction(e -> {
numberSet.remove(number);
});
Button add = new Button("add");
add.setOnAction(e -> {
numberSet.add(number);
});
BorderPane content = new BorderPane(circles);
content.setBottom(new HBox(10, remove, add));
return content;
}
@Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(createContent()));
stage.setTitle(FXUtils.version());
stage.show();
}
public static void main(String[] args) {
launch(args);
}
@SuppressWarnings("unused")
private static final Logger LOG = Logger
.getLogger(SetContainsBinding.class.getName());
}