java - 将 ObservableSet 中值的存在与属性绑定(bind)

标签 java javafx properties javafx-8

假设我有一个 ObservableSet<Integer>整数。我想画一个形状,或者更具体地说是一个圆圈。

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

是否可以绑定(bind)visibleProperty() JavaFX 和 JDK8 集合内是否存在该形状的值?

例如,如果集合包含 5将形状的可见性设置为 true ,否则false 。一般来说,是否有任何方法可以绑定(bind)到集合内部元素的存在?

最佳答案

看起来没有什么现成的东西(至少我找不到任何东西),所以我们必须自己做。基本上有两个选择:

  • 向 ObservableSet 注册 SetChangeListener,收到通知后手动更新 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());

}

关于java - 将 ObservableSet 中值的存在与属性绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55827932/

相关文章:

java - 如何在 Tomcat 7 中设置带有 MySql 连接池的 Realm ?

java - Springboot+JPA(Hibernate)+Oracle AbstractMethodError 未定义或继承 isValid(int) 的实现

java - 在 Reactor 项目中的单个 Maven 构建中运行 Java 应用程序和 Web 应用程序

带有 -fx-background-color 的 JavaFX setStyle 仅绘制 TextArea 的边缘

java - 我使用 setOnMouseEntered 并且有一些异常(exception)

java - Spring 中读取属性文件的不同行为

java - Safari 5/iOS,WebSocket 握手有时有效

java - openjfx 1.8 不包含 javafx.fxml 包

c# - convert to auto-property 是什么意思?

ms-access - Access 报告 - 隐藏字段、标签和其他基于数据的元素