1 回答
TA贡献1845条经验 获得超8个赞
这个答案只涵盖了问题的一部分:如何确保单元格图形属性的侦听器只注册一次(如果我们无法控制何时设置图形)。
涉及的步骤:
定义一个安装“真实”监听器的 InvalidationListener(注意:必须是一个可以稍后删除的字段)
在实例化时在单元格的图形属性上注册监听器
实施“真实”方法的注册以删除初始图形侦听器以及安装所需的任何东西
代码片段(注意:监听 selected 属性不是一个好主意,因为它会在数据更改时触发,而不仅仅是在用户单击复选框时触发!):
listView.setCellFactory(factory -> {
CheckBoxListCell<Model> cell = new CheckBoxListCell<Model>() {
// a listener on the graphicProperty: it installs the "real" listener
InvalidationListener graphicListener = g -> {
// installs the "real" listener on the graphic control once it is available
registerUIListener();
};
{
// install the graphic listener at instantiation
graphicProperty().addListener(graphicListener);
}
/** method to install a listener on a property of the graphic control
* and unregisters the initially installed listener
*/
private void registerUIListener() {
if (!(getGraphic() instanceof CheckBox)) throw new IllegalStateException("checkBox expected");
graphicProperty().removeListener(graphicListener);
((CheckBox) getGraphic()).selectedProperty().addListener(
(observable, oldValue, newValue) -> listView.getSelectionModel().select(getItem()));
}
};
cell.setSelectedStateCallback(Model::selectedProperty);
return cell;
});
添加回答
举报
