Checkbox 选中复选框将选择整行进行删除

Checkbox 选中复选框将选择整行进行删除,checkbox,javafx-8,delete-row,Checkbox,Javafx 8,Delete Row,我对JavaFX非常陌生。我创建了这段代码,但当我点击复选框时,我不知道如何选择整行 我在单击行(如果选中)时实现了删除功能。但现在我还想添加复选框选择 我注意到的一件事是,当我删除该行时,下一个复选框将自动选中 我的代码在这里: package com.wf.sapphire.client.feature.cls; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanP

我对JavaFX非常陌生。我创建了这段代码,但当我点击复选框时,我不知道如何选择整行

我在单击行(如果选中)时实现了删除功能。但现在我还想添加复选框选择

我注意到的一件事是,当我删除该行时,下一个复选框将自动选中

我的代码在这里:

package com.wf.sapphire.client.feature.cls;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.util.Callback;

import javax.inject.Inject;

import com.wf.sapphire.client.javafx.ViewModelControllerBase;

public class ClsMainController extends ViewModelControllerBase<ClsMainViewModel> {

    @Inject
    protected ClsMainController(final ClsMainViewModel clsMainViewModel) {      
        super(clsMainViewModel);
    }

    @FXML
    public ComboBox<String> clsComboData;
    @FXML
    public StackPane statckPaneId;  
    @FXML
    private TableView<Person> tblViewer = new TableView();
    @FXML
    public Button delBtn;
    @FXML
    Parent root;

    private final TableView<Person> table = new TableView<>();
    final ObservableList<Person> data = FXCollections.observableArrayList(
            new Person(true, "Jacob", "Smith", "jacob.smith@example.com"),
            new Person(true, "Isabella", "Johnson", "isabella.johnson@example.com"),
            new Person(true, "Ethan", "Williams", "ethan.williams@example.com"),
            new Person(true, "Emma", "Jones", "emma.jones@example.com"),
            new Person(true, "Michael", "Brown", "michael.brown@example.com")
        );

    public void initialize() {
        //Set<Person> selection = new HashSet<Person>(tblViewer.getSelectionModel().getSelectedItems());
        /*System.out.println("\n In the initialize \n");
        System.out.println("READ");
        System.out.println(this.getClass().getSimpleName() + ".initialize");*/ 
    }


    @FXML
    private void onSubmitHandler(ActionEvent event) {

        System.out.println(clsComboData.getValue());
        System.out.println("Button Pressed");


        //"Invited" column
        TableColumn invitedCol = new TableColumn<Person, Boolean>();

        invitedCol.setText("Invited");

        invitedCol.setMinWidth(50);

        invitedCol.setCellValueFactory(new PropertyValueFactory("invited"));
        // Create checkboxes
        invitedCol.setCellFactory(new Callback<TableColumn<Person, Boolean>, TableCell<Person, Boolean>>() {
            public TableCell<Person, Boolean> call(TableColumn<Person, Boolean> p) {
                //System.out.println("Checkbox Pressed");
                //private TableView<Person> tblViewer = new TableView();
                CheckBoxTableCell<Person, Boolean> checkBox = new CheckBoxTableCell();

                return checkBox;

            }
        });              

        TableColumn firstNameCol = new TableColumn("First Name");
        firstNameCol.setCellValueFactory(
                new PropertyValueFactory<Person, String>("firstName"));

        TableColumn lastNameCol = new TableColumn("Last Name");
        lastNameCol.setCellValueFactory(
                new PropertyValueFactory<Person, String>("lastName"));

        TableColumn emailNameCol = new TableColumn("Email");
        emailNameCol.setCellValueFactory(
                new PropertyValueFactory<Person, String>("email"));

        //Set cell factory for cells that allow editing
        Callback<TableColumn, TableCell> cellFactory =
                new Callback<TableColumn, TableCell>() {
            public TableCell call(TableColumn p) {

                return new EditingCell();

            }
        };
        emailNameCol.setCellFactory(cellFactory);
        firstNameCol.setCellFactory(cellFactory);
        lastNameCol.setCellFactory(cellFactory);

        //Set handler to update ObservableList properties. Applicable if cell is edited        
        updateObservableListProperties(emailNameCol, firstNameCol, lastNameCol);

        // Clear the tableview for next table
        tblViewer.getColumns().clear();
        // Push the data to the tableview
        tblViewer.setItems(data);
        tblViewer.setEditable(true);
        // Add the columns
        tblViewer.getColumns().addAll(invitedCol,firstNameCol, lastNameCol,emailNameCol);
        tblViewer.getSelectionModel().setCellSelectionEnabled(true);


        CheckBox cb = new CheckBox("Select all");
        cb.selectedProperty().addListener(new ChangeListener<Boolean>() {
            public void changed(ObservableValue<? extends Boolean> ov,
                    Boolean old_val, Boolean new_val) {
                if (new_val) {
                    for (Person p : data) {
                        p.invited.set(true);
                    }

                }


            }
        });        
        //tblViewer.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);        
    }

    @FXML
    private void onDeleteHandler(ActionEvent event){

        data.removeAll(tblViewer.getSelectionModel().getSelectedItems());
        tblViewer.getSelectionModel().clearSelection();

    }


    public static class Person {
        private final BooleanProperty invited;
        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;
        private final SimpleStringProperty email;

        private Person(boolean invited, String fName, String lName, String email) {
            this.invited = new SimpleBooleanProperty(invited);
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
            this.email = new SimpleStringProperty(email);

            this.invited.addListener(new ChangeListener<Boolean>() {
                public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {

                    System.out.println(getFirstName() + " invited: " + t1);

                }
            });
        }

        public boolean getInvited() {
            return invited.get();
        }   

        public String getFirstName() {
            return firstName.get();
        }
        public void setFirstName(String fName) {
            firstName.set(fName);
        }

        public String getLastName() {
            return lastName.get();
        }
        public void setLastName(String fName) {
            lastName.set(fName);
        }

        public String getEmail() {
            return email.get();
        }
        public void setEmail(String fName) {
            email.set(fName);
        }

    }

    private void updateObservableListProperties(TableColumn emailCol, TableColumn firstNameCol,
            TableColumn lastNameCol) {
        //System.out.println("updateObservableListProperties");
        //Modifying the email property in the ObservableList

        emailCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>() {
            @Override
            public void handle(CellEditEvent<Person, String> t) {
                //System.out.println("setOnEditCommit");
                ((Person) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())).setEmail(t.getNewValue());

            }
        });

        //Modifying the firstName property in the ObservableList

        firstNameCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>() {
            @Override
            public void handle(CellEditEvent<Person, String> t) {
                //  System.out.println("firstNameCol");
                ((Person) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())).setFirstName(t.getNewValue());

            }
        });

        //Modifying the lastName property in the ObservableList

        lastNameCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>() {
            @Override
            public void handle(CellEditEvent<Person, String> t) {
                //  System.out.println("lastNameCol");
                ((Person) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())).setLastName(t.getNewValue());

            }
        });

    }
  //CheckBoxTableCell for creating a CheckBox in a table cell
    public static class CheckBoxTableCell<S, T> extends TableCell<S, T> {

        private final CheckBox checkBox;
        private ObservableValue<T> ov;

        public CheckBoxTableCell() {
            //System.out.println("CheckBoxTableCell");
            this.checkBox = new CheckBox();

            this.checkBox.setAlignment(Pos.CENTER);

            setAlignment(Pos.CENTER);

            setGraphic(checkBox);

        }

        @Override
        public void updateItem(T item, boolean empty) {
            //System.out.println("updateItem");
            super.updateItem(item, empty);

            if (empty) {

                setText(null);

                setGraphic(null);

            } else {

                setGraphic(checkBox);

                if (ov instanceof BooleanProperty) {

                    checkBox.selectedProperty().unbindBidirectional((BooleanProperty) ov);

                }

                ov = getTableColumn().getCellObservableValue(getIndex());

                if (ov instanceof BooleanProperty) {

                    checkBox.selectedProperty().bindBidirectional((BooleanProperty) ov);

                }

            }

        }
    }

    // EditingCell - for editing capability in a TableCell
    public static class EditingCell extends TableCell<Person, String> {

        private TextField textField;

        public EditingCell() {
            //System.out.println("EditingCell");
        }

        @Override
        public void startEdit() {
            //System.out.println("startEdit");
            super.startEdit();



            if (textField == null) {

                createTextField();

            }

            setText(null);

            setGraphic(textField);

            textField.selectAll();

        }

        @Override
        public void cancelEdit() {
            //System.out.println("cancelEdit");
            super.cancelEdit();

            setText((String) getItem());

            setGraphic(null);

        }

        @Override
        public void updateItem(String item, boolean empty) {
            //System.out.println("updateItem");
            super.updateItem(item, empty);

            if (empty) {

                setText(null);

                setGraphic(null);

            } else {

                if (isEditing()) {

                    if (textField != null) {

                        textField.setText(getString());

                    }

                    setText(null);

                    setGraphic(textField);

                } else {

                    setText(getString());

                    setGraphic(null);

                }

            }

        }

        private void createTextField() {
            //System.out.println("createTextField");
            textField = new TextField(getString());

            textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);

            textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
                @Override
                public void handle(KeyEvent t) {

                    if (t.getCode() == KeyCode.ENTER) {

                        commitEdit(textField.getText());

                    } else if (t.getCode() == KeyCode.ESCAPE) {

                        cancelEdit();

                    }

                }
            });

        }

        private String getString() {
            //System.out.println("getString");
            return getItem() == null ? "" : getItem().toString();

        }
    }
}
package com.wf.sapphire.client.feature.cls;
导入javafx.beans.property.BooleanProperty;
导入javafx.beans.property.SimpleBoleAnProperty;
导入javafx.beans.property.SimpleStringProperty;
导入javafx.beans.value.ChangeListener;
导入javafx.beans.value.observeValue;
导入javafx.collections.FXCollections;
导入javafx.collections.ObservableList;
导入javafx.event.ActionEvent;
导入javafx.event.EventHandler;
导入javafx.fxml.fxml;
导入javafx.geometry.Pos;
导入javafx.scene.Parent;
导入javafx.scene.control.Button;
导入javafx.scene.control.CheckBox;
导入javafx.scene.control.ComboBox;
导入javafx.scene.control.TableCell;
导入javafx.scene.control.TableColumn;
导入javafx.scene.control.TableColumn.CellEditEvent;
导入javafx.scene.control.TableView;
导入javafx.scene.control.TextField;
导入javafx.scene.control.cell.PropertyValueFactory;
导入javafx.scene.input.KeyCode;
导入javafx.scene.input.KeyEvent;
导入javafx.scene.layout.StackPane;
导入javafx.util.Callback;
导入javax.inject.inject;
导入com.wf.sapphire.client.javafx.ViewModelControllerBase;
公共类CLSMAInControl扩展了ViewModelControllerBase{
@注入
受保护的ClsMainController(最终ClsMainViewModel ClsMainViewModel){
超级(clsMainViewModel);
}
@FXML
公共组合框clsComboData;
@FXML
公共StackPane statckPaneId;
@FXML
private TableView tblViewer=new TableView();
@FXML
公共按钮delBtn;
@FXML
亲本根;
private final TableView table=new TableView();
最终ObservableList数据=FXCollections.observableArrayList(
新人(对,“雅各布”、“史密斯”、“雅各布”。smith@example.com"),
新人(对,“伊莎贝拉”、“约翰逊”、“伊莎贝拉”。johnson@example.com"),
新人(对,“伊桑”,“威廉姆斯”,“伊桑。williams@example.com"),
新人(真的,“艾玛”、“琼斯”、“艾玛”。jones@example.com"),
新人(真的,“迈克尔”,“布朗”,“迈克尔。brown@example.com")
);
公共无效初始化(){
//Set selection=new HashSet(tblViewer.getSelectionModel().getSelectedItems());
/*System.out.println(“\n在初始化中”);
系统输出打印项次(“读取”);
System.out.println(this.getClass().getSimpleName()+“.initialize”);*/
}
@FXML
私有void onSubmitHandler(ActionEvent事件){
System.out.println(clsComboData.getValue());
System.out.println(“按下按钮”);
//“邀请”专栏
TableColumn invitedCol=新建TableColumn();
invitedCol.setText(“受邀”);
受邀的COL.设置最小宽度(50);
invitedCol.setCellValueFactory(新属性值工厂(“受邀”);
//创建复选框
invitedCol.setCellFactory(新回调(){
公共TableCell调用(TableP列){
//System.out.println(“按下复选框”);
//private TableView tblViewer=new TableView();
CheckBoxTableCell checkBox=新的CheckBoxTableCell();
返回复选框;
}
});              
TableColumn firstNameCol=新的TableColumn(“名字”);
firstNameCol.setCellValueFactory(
新财产价值工厂(“名字”);
TableColumn lastNameCol=新的TableColumn(“姓氏”);
lastNameCol.setCellValueFactory(
新财产价值工厂(“姓氏”);
TableColumn emailNameCol=新的TableColumn(“电子邮件”);
emailNameCol.setCellValueFactory(
新物业价值工厂(“电子邮件”);
//为允许编辑的单元格设置单元格工厂
回叫手机工厂=
新回调函数(){
公共TableCell调用(TableP列){
返回新的EditingCell();
}
};
emailNameCol.setCellFactory(cellFactory);
firstNameCol.setCellFactory(cellFactory);
lastNameCol.setCellFactory(cellFactory);
//设置处理程序以更新ObservableList属性。如果单元格已编辑,则适用
updateObservableListProperties(emailNameCol、firstNameCol、lastNameCol);
//清除下一个表的tableview
tblViewer.getColumns().clear();
//将数据推送到tableview
tblViewer.setItems(数据);
tblViewer.setEditable(真);
//添加列
tblViewer.getColumns().addAll(invitedCol、firstNameCol、lastNameCol、emailNameCol);
tblViewer.getSelectionModel().setCellSelectionEnabled(true);
复选框cb=新复选框(“全选”);
cb.selectedProperty().addListener(新的ChangeListener()){
公共空隙改变(观察值Try

public CheckBoxTableCell()
{
//System.out.println(“CheckBoxTableCell”);
this.checkBox=新建复选框();
此.checkBox.setAlignment(位置中心);
设置对齐(位置中心);
复选框.selectedProperty().addListener(新的ChangeListener())
{
@凌驾

public void已更改(ObservalEvalue工作得很好。但我在帖子中提到的一件事是,当我删除一行时,下一行已自动选中复选框。有什么想法/解决方案吗?@user3910235,在我的测试代码中,删除所选项目后,下一行未被选中。由于tblViewer.getSelectionModel()的原因.clearSelection();我已经删除了那一行。但同样的问题仍然存在。哦,我的意思是,在添加那一行之后,删除操作按预期进行@user3910235删除任何一行之后,您是否理解我的问题
public CheckBoxTableCell()
{
    //System.out.println("CheckBoxTableCell");
    this.checkBox = new CheckBox();
    this.checkBox.setAlignment( Pos.CENTER );
    setAlignment( Pos.CENTER );

    checkBox.selectedProperty().addListener( new ChangeListener<Boolean>()
    {
        @Override
        public void changed( ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue )
        {
            if ( newValue )
            {
                getTableView().getSelectionModel().select( getIndex() );
            }
            else
            {
                getTableView().getSelectionModel().clearSelection( getIndex() );
            }
        }
    } );

    setGraphic( checkBox );

}