【发布时间】:2016-03-09 07:57:23
【问题描述】:
我有一个填写结果列表的 Worker。 ListView 绑定到此结果列表,并在部分结果可用时立即填充。效果很好!
然后有一个按钮可以处理列表中的项目。因此,只要列表为空,就应该禁用它。这适用于所有其他列表。但不适合这个。
我通过剥离 UI 组件并仅使用属性来减少示例。结果是一样的。要么存在某种错误,要么我不明白绑定是如何工作的。
我希望在这方面有任何帮助。
只需将此代码放入 main() 方法中,您就会看到问题所在。我正在使用 Java 1.8 更新 74。
// a list of items, e.g. in a list view
ReadOnlyObjectWrapper<ObservableList<String>> items = new ReadOnlyObjectWrapper<>(
FXCollections.observableArrayList(new ArrayList<>()));
// a button that is disabled if there are no items
BooleanProperty disabled = new SimpleBooleanProperty();
disabled.bind(Bindings.createBooleanBinding(() -> Boolean.valueOf(items.get().isEmpty()), items));
// a list with results, e.g. from a worker
ReadOnlyObjectWrapper<ObservableList<String>> results = new ReadOnlyObjectWrapper<>(
FXCollections.observableArrayList(new ArrayList<>()));
// the items are bound to the results (the list is showing partial result then)
items.bind(results);
// the button is still disabled
System.out.println(disabled.get()); // expected true !WORKS!
// add a result (should inform the items and the button)
results.get().add("Hello");
// both list should be identical now
System.out.println(results.get()); // expected [Hello] !WORKS!
System.out.println(items.get()); // expected [Hello] !WORKS!
// the button should not be disabled anymore
System.out.println(disabled.get()); // expected false !FALIED!
// try to re-bind the button
disabled.unbind();
disabled.bind(Bindings.createBooleanBinding(() -> Boolean.valueOf(items.get().isEmpty()), items));
System.out.println(disabled.get()); // expected false !WORKS!
【问题讨论】:
标签: java data-binding javafx