假设我有一个ObservableSet<Integer>
整数。我想绘制一个形状,或更具体地讲是一个圆形。
Circle circle = new Circle(5);
circle.setFill(Color.RED);
是否可以将这种形状的visibleProperty()
绑定到JavaFX和JDK8集合中的值的存在?
例如,如果set包含5
,则将形状的可见性设置为true
,否则设置false
。通常有什么方法可以绑定到集合内部元素的存在吗?
答案 0 :(得分:3)
看起来好像没有开箱即用的东西(至少我找不到任何东西),所以我们必须自己做。基本上有两个选择:
两者都感到笨拙,可能有更好的方法。两者的示例:
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());
}