Why does JavaFX table.getItems().clear() clear the ObservableList as well

送分小仙女□ 提交于 2020-01-06 03:55:07

问题


I've a JavaFX table defined as:

TableView<Person> table = new TableView<>;
//Person Class contains firstName,lastName & email properties
//table has three columns First Name, Last Name & Email

An ObservableList of Persons

ObservableList<Person> persons = FXCollections.observableArrayList();

A background service, which task is to populate the table dynamically by adding entries(Person objects) to the ObservableList persons.

table is binded as:

table.itemsProperty().bind(service.valueProperty());

Everything is working fine... but I've recently found that if I clear the table items by

table.getItems().clear();

It does not only clears the table, but also the ObservableList persons. I'm wondering if this a bidirectional binding? Even if I unbind it before calling getItems().clear() on the table, it produces same result. Could someone explain what the point I'm not getting here?


回答1:


When you set the itemsProperty of a TableView, what you are actually doing is to set the reference (pointer) stored in the property, to point to the specified ObservableList, rather that making an exact copy of the specified list.

Therefore, when you call getItems, it returns the reference to the specified list.

Therefore, if you call clear() on this list, you will clear the original ObservableList.


Note:

In most of the cases the binding what you have tried is not necessary:

table.itemsProperty().bind(service.valueProperty());

and it is enough to simply set the itemsProperty like

table.setItems(service.valueProperty().get());

The binding is only necessary if you plan that the reference stored in valueProperty will point to another list in runtime. In most of the cases it is enough that the table gets notifications on the changes of the list.



来源:https://stackoverflow.com/questions/38223115/why-does-javafx-table-getitems-clear-clear-the-observablelist-as-well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!