1 回答

TA貢獻1845條經驗 獲得超8個贊
這個答案只涵蓋了問題的一部分:如何確保單元格圖形屬性的偵聽器只注冊一次(如果我們無法控制何時設置圖形)。
涉及的步驟:
定義一個安裝“真實”監聽器的 InvalidationListener(注意:必須是一個可以稍后刪除的字段)
在實例化時在單元格的圖形屬性上注冊監聽器
實施“真實”方法的注冊以刪除初始圖形偵聽器以及安裝所需的任何東西
代碼片段(注意:監聽 selected 屬性不是一個好主意,因為它會在數據更改時觸發,而不僅僅是在用戶單擊復選框時觸發?。?/p>
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;
});
添加回答
舉報