如何在 JavaFX 和 FXML 的表视图中创建一个带有所有复选框的选择的复选框?

How to make a checkbox with a selection of all checkboxes in the tableview on JavaFX and FXML?

大家好。遇到这样的问题。单击顶部的复选框时,有必要在 table 中的整个列表旁边的框中切换复选框。然后当你点击按钮时,删除选中的记录,从MySQL数据库中删除选中的记录。

这是完成的。

PersonUnpersonValueFactoryController.java

package usersapp.controller;

import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import usersapp.model.Person;

public class PersonUnpersonValueFactory implements Callback<TableColumn.CellDataFeatures<Person, CheckBox>, ObservableValue<CheckBox>> {

    @Override
    public ObservableValue<CheckBox> call(TableColumn.CellDataFeatures<Person, CheckBox> param) {
        Person person = param.getValue();
        CheckBox checkBox = new CheckBox();
        checkBox.selectedProperty().setValue(person.isUnperson());

        checkBox.selectedProperty().addListener((ov, old_val, new_val) -> {
            person.setUnperson(new_val);
            System.out.println(new_val);
        });
        return new SimpleObjectProperty<>(checkBox);
    }
}

Person.java

public class Person {

private Boolean unperson;

    ...

    //unperson
    public Boolean isUnperson() {
        return this.unperson;
    }

    public void setUnperson(Boolean unperson){
        this.unperson = unperson;
    }

    ...

}

PersonView.fxml

<?import usersapp.controller.PersonUnpersonValueFactory?>

...

<TableView fx:id="personTable" editable="true" layoutX="7.0" layoutY="53.0" prefHeight="285.0" prefWidth="378.0" tableMenuButtonVisible="true" AnchorPane.bottomAnchor="4.0" AnchorPane.leftAnchor="7.0" AnchorPane.rightAnchor="7.0" AnchorPane.topAnchor="53.0">
                     <columns>
                        <TableColumn prefWidth="50.0" style="-fx-alignment: CENTER;">
                           <cellValueFactory>
                              <PersonUnpersonValueFactory />
                           </cellValueFactory>
                           <graphic>
                              <CheckBox mnemonicParsing="false" />
                           </graphic>
                        </TableColumn>
                        ...
                     </columns>
                  </TableView>

非常感谢您的帮助。

您只需要 "master" CheckBox 上的侦听器来观察 selectedProperty 的更改。然后您可以使用它来遍历 TableView 项并更新它们的 selectedProperty

Note that with the limited code you've provided, I need to make some assumptions on how your data model is constructed.

checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> {

    // Loop through entire TableView to set the selected property for each Item
    for (Item item : tableView.getItems()) {
        item.setSelected(newValue);
    }
});