选中的复选框将选择整行以进行删除

时间:2015-04-10 13:01:42

标签: checkbox javafx-8 delete-row

我是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();

        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试

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

}