我制作了自定义列表视图,以下是代码:
ListView<Sector> sectorList = new ListView();
sectorList.setStyle("-fx-font-size: 21px;");
sectorList.setItems(data2);
sectorList.setCellFactory(new Callback<ListView<Sector>, ListCell<Sector>>() {
@Override
public ListCell<Sector> call(ListView<Sector> param) {
return new XCell();
}
});
class XCell extends ListCell<Sector>{
@Override
protected void updateItem(Sector sector, boolean empty){
super.updateItem(sector, empty);
if(!empty){
CheckBox checkbox = new CheckBox(sector.getName());
checkbox.setStyle("-fx-font-weight: bold;");
checkbox.setSelected(true);
Label label = new Label(" "+sector.getDescription());
label.setStyle("-fx-font-style: italic;");
VBox root = new VBox(5);
root.setPadding(new Insets(8));
root.getChildren().addAll(checkbox,label);
setGraphic(root);
}else{
setGraphic(null);
}
}
}
有没有办法遍历listview的项目并检查是否选中了复选框?怎么样?
答案 0 :(得分:-2)
您可以向CheckBox
添加Sector
字段,并使用updateItem
方法进行分配:
sector.setCheckBox(checkbox);
然后,您可以遍历ListView中的所有元素:
sectorList.getItems().forEach((sector) -> {
boolean selected = sector.getCheckBox().isSelected();
// do whatever needs to be done
})
<强>更新强>
您还可以向BooleanProperty
添加Sector
并将其绑定到CheckBox的selectedProperty,如下所示:
checkbox.selectedProperty().bind(selector.yourBooleanProperty);
并在foreach循环中检查此属性