简体   繁体   中英

How to check if the checkbox is selected or not

I made a custom listview, following is the code:

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);
        }
    }
}

在此处输入图像描述

Is there a way to loop through the listview's items and check if the checkbox is selected or not? How?

There is isSelected() method in JavaFX for the same.

You could add a CheckBox field to Sector and assign it in the updateItem method:

sector.setCheckBox(checkbox);

You can then iterate through all the elements in your ListView:

sectorList.getItems().forEach((sector) -> {
    boolean selected = sector.getCheckBox().isSelected();
    // do whatever needs to be done
})

Update

You could also add a BooleanProperty to Sector and bind it to the selectedProperty of the CheckBox like this:

checkbox.selectedProperty().bind(selector.yourBooleanProperty);

And the check this property in the foreach loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM