JavaFx,实现CheckBox复选框的全选和全不选

JavaFx,实现CheckBox复选框的全选和全不选。子复选框单个全部选择后,全选框也会被选择;子复选框单个全部不选后,全选框也会被不选。

fxml文件中:



   
        
       
           
               
           
       
   
   
       
   

Controller文件中:

@FXML private TableView table;
@FXML private CheckBox selectAll;
@FXML private TableColumn select;
/**
 * 全选框触发事件,勾选则所有checkbox复选框都勾选,不勾选则所有checkbox复选框不勾选
 */
public void selectBox(){
    ObservableList items = table.getItems();
    if (selectAll.isSelected()){
        for (CxCadreInfo cxCadreInfo:items){
            cxCadreInfo.cb.setSelect(true);
        }
    }else {
        for (CxCadreInfo cxCadreInfo:items){
            cxCadreInfo.cb.setSelect(false);
        }
    }
}

//在init初始化方法中写复选框监听事件

	//初始化所有checkbox复选框
    select.setCellValueFactory(cellData ->cellData.getValue().cb.getCheckBox());
    //初始化复选框-监听-所有checkbox复选框都勾选则全选框勾选,所有checkbox复选框不勾选则全选框不勾选
    Callback, TableCell> cellFactory1 =
            new Callback, TableCell>() {
                public TableCell call(TableColumn p) {
                    TableCell cell = new TableCell() {
                        @Override
                        public void updateItem(CheckBox item, boolean empty) {
                            super.updateItem(item, empty);
                            setGraphic(item);
                            if (item!= null) {
                                item.selectedProperty().addListener(new ChangeListener() {
                                    @Override
                                    public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) {
                                        boolean booSelectAll = true;
                                        ObservableList items2 = table.getItems();
                                        for (CxCadreInfo cxCadreInfo2:items2){
                                            if (!cxCadreInfo2.cb.isSelected()) {
                                                booSelectAll = false;
                                                break;
                                            }
                                        }
                                        selectAll.setSelected(booSelectAll);
                                    }
                                });
                            }
                        }
                    };
                    return cell;
                }
            };
    select.setCellFactory(cellFactory1);

效果:

JavaFx,实现CheckBox复选框的全选和全不选_第1张图片
JavaFx,实现CheckBox复选框的全选和全不选_第2张图片

你可能感兴趣的:(技术积累,JavaFx复选框)