met*_*sim 9 java binding javafx observable javafx-2
我有一种情况,我想绑定BooleanProperty到一个ObservableList包裹在一个非空状态ObjectProperty.
这是我正在寻找的行为的基本概要:
ObjectProperty<ObservableList<String>> obp = new SimpleObjectProperty<ObservableList<String>>();
BooleanProperty hasStuff = new SimpleBooleanProperty();
hasStuff.bind(/* What goes here?? */);
// ObservableProperty has null value
assertFalse(hasStuff.getValue());
obp.set(FXCollections.<String>observableArrayList());
// ObservableProperty is no longer null, but the list has not contents.
assertFalse(hasStuff.getValue());
obp.get().add("Thing");
// List now has something in it, so hasStuff should be true
assertTrue(hasStuff.getValue());
obp.get().clear();
// List is now empty.
assertFalse(hasStuff.getValue());
Run Code Online (Sandbox Code Playgroud)
我想在类中使用构建器,Bindings而不是实现一系列自定义绑定.
该Bindings.select(...)方法理论上做了我想要的,除了没有Bindings.selectObservableCollection(...)并且从通用中转换返回值 select(...)并将其传递给Bindings.isEmpty(...)不起作用.也就是说,结果如下:
hasStuff.bind(Bindings.isEmpty((ObservableList<String>) Bindings.select(obp, "value")));
Run Code Online (Sandbox Code Playgroud)
导致ClassCastException:
java.lang.ClassCastException: com.sun.javafx.binding.SelectBinding$AsObject cannot be cast to javafx.collections.ObservableList
Run Code Online (Sandbox Code Playgroud)
这个用例是否可以仅使用BindingsAPI?
根据@fabian的回答,这是有效的解决方案:
ObjectProperty<ObservableList<String>> obp = new SimpleObjectProperty<ObservableList<String>>();
ListProperty<String> lstProp = new SimpleListProperty<>();
lstProp.bind(obp);
BooleanProperty hasStuff = new SimpleBooleanProperty();
hasStuff.bind(not(lstProp.emptyProperty()));
assertFalse(hasStuff.getValue());
obp.set(FXCollections.<String>observableArrayList());
assertFalse(hasStuff.getValue());
obp.get().add("Thing");
assertTrue(hasStuff.getValue());
obp.get().clear();
assertFalse(hasStuff.getValue());
Run Code Online (Sandbox Code Playgroud)
我没有看到使用Bindings API的方法.ObservableList没有属性为空,因此您无法使用
Bindings.select(obp, "empty").isEqualTo(true)
Run Code Online (Sandbox Code Playgroud)
和
ObjectBinding<ObservableList<String>> lstBinding = Bindings.select(obp);
hasStuff.bind(lstBinding.isNotNull().and(lstBinding.isNotEqualTo(Collections.EMPTY_LIST)));
Run Code Online (Sandbox Code Playgroud)
不起作用,因为它只在列表更改时更新,而不是在内容更改时更新(即第三个断言失败).
但是您必须创建的自定义绑定链非常简单:
SimpleListProperty lstProp = new SimpleListProperty();
lstProp.bind(obp);
hasStuff.bind(lstProp.emptyProperty());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3074 次 |
| 最近记录: |