JavaFX 8, ListView with Checkboxes scrollpane issue

偶尔善良 提交于 2019-12-02 10:14:19

The Callback is used to retrieve the property for the checked state when the item is associated with a cell. The item may be removed from a cell and put in a new one at any time. This is how ListView (and similar controls like TableView) works. CheckBoxListCell simply gets the checked state property every time a new item is associated with the cell.

The return value is also used to set the initial state of the CheckBox. Since you do not properly initialize the property with the correct value the initial state is not preserved.

Also note that it makes little sense to update the value of the property to the new value in the change listener. It happens anyway.

Since BooleanProperty is a wrapper for primitive boolean the possible values are true and false; the ChangeListener only gets called when !Objects.equals(oldValue, newValue) you can be sure that isNowSelected = !wasSelected.

Of course you also need to return the value:

@Override
public ObservableValue < Boolean > call(Bean item) {
    final String value = item.toString();
    BooleanProperty observable = new SimpleBooleanProperty(beanChoices.contains(value));
    observable.addListener((obs, wasSelected, isNowSelected) -> {
        if (isNowSelected) {
            beanChoices.add(value);
        } else {
            beanChoices.remove(value);
        }
    });
    return observable;
}

I also recommend using a Collection of Beans instead of relying on the string representation of the objects. toString many not produce unique results and Beans.equals would be the better choice to compare the objects.

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