Bind existence of a value in ObservableSet to property

0x1C1B :

Let's say I've an ObservableSet<Integer> of integers. I want to draw a shape, or to be more specific a circle.

Circle circle = new Circle(5);
circle.setFill(Color.RED);

Is it posible to bind the visibleProperty() of that shape to the existence of value inside of the set for JavaFX and the JDK8?

For example if set contains 5 set visibility of the shape to true, otherwise false. Are there any approaches for binding to existence of elements inside of collections in general?

kleopatra :

Looks like there's nothing out-of-the-box (at least I couldn't find anything), so we have to do it ourselves. Basically two options:

  • register a SetChangeListener to the ObservableSet, on notification update a BooleanProperty manually
  • wrap the ObservableSet into a SetProperty and create a BooleanBinding that queries a Callable on receiving any change

Both feel a bit clumsy, there might be better approaches. An example for both:

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());

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=133131&siteId=1
Recommended