ListView我在使用 a时遇到问题CheckBoxListCell。当我选中/取消选中某个项目时,该项目未被选中/聚焦,这是预期的,因为 CheckBox 也是该项目的一部分,而不仅仅是文本部分。
这是一个简单的代码,您可以验证它。
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
import javafx.scene.control.cell.CheckBoxListCell;
import lombok.Getter;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML private ListView<Model> listView;
@Override
public void initialize(URL location, ResourceBundle resources) {
// without selection
// listView.setCellFactory(CheckBoxListCell.forListView(Model::getSelected));
// actual "bad" solution
listView.setCellFactory(factory -> {
CheckBoxListCell<Model> cell = new CheckBoxListCell<Model>() {
@Override
public void updateItem(Model item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
return;
}
((CheckBox) getGraphic()).selectedProperty().addListener(
(observable, oldValue, newValue) -> listView.getSelectionModel().select(getItem()));
}
};
cell.setSelectedStateCallback(Model::getSelected);
return cell;
});
ObservableList<Model> items = FXCollections.observableArrayList();
items.add(new Model("A", true));
items.add(new Model("B", true));
items.add(new Model("C", false));
listView.setItems(items);
}
如您所见,我找到了一个解决方案,或者更确切地说是一个肮脏的解决方法,但我不太喜欢它,因为它在每个 updateItem 时都会被调用,并且它会添加 n 次监听器,这不是很好。
任何其他想法/解决方案,当我选中/取消选中组合框时,我如何才能实现这一点,整个项目都被选中/聚焦。
精慕HU
相关分类