JavaFX tableview:在编辑模式下,默认情况下,顶部单元格保存来自波纹管单元格的数据

时间:2018-07-02 04:28:16

标签: java javafx

我对JavaFX非常陌生。我有一个具有多个列和行的表。可以在表格顶部添加新行的位置。还启用了编辑单元格。但是我面临一个问题。

当我在顶部添加新行并进行编辑时,单元格将在编辑开始时自动用波纹管单元格中的值填充!但是我不想要那个。是像excel这样的功能吗?如果是,我该如何制止呢?这是示例图片和我的自定义EditingCell.java

enter image description here

class EditingCell <S, T>extends TableCell<S, T> {

    private TextField textField;

    public EditingCell() {
    }

    @Override
    public void startEdit() {
        if (!isEmpty()) {
            super.startEdit();
            if (textField == null) {
                createTextField();
            }

            setGraphic(textField);
            setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            // textField.selectAll();
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    textField.requestFocus();
                    textField.selectAll();
                }
            });
        }
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();

        setText((String) getItem());
        setGraphic(null);
         setContentDisplay(ContentDisplay.TEXT_ONLY);
    }

    @Override
    public   void updateItem (T item, boolean empty) {
        super.updateItem(item, empty);

        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            if (isEditing()) {
                if (textField != null) {
                    textField.setText(getString());
                }
                setGraphic(textField);
                setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            } else {
                setText(getString());
                setContentDisplay(ContentDisplay.TEXT_ONLY);
            }
        }
    }
    @Override
        public void commitEdit(T item) {

            if (! isEditing() && ! item.equals(getItem())) {
                TableView<S> table = getTableView();
                if (table != null) {
                    TableColumn<S, T> column = getTableColumn();
                    CellEditEvent<S, T> event = new CellEditEvent<>(table, 
                            new TablePosition<S,T>(table, getIndex(), column), 
                            TableColumn.editCommitEvent(), item);
                    Event.fireEvent(column, event);
                }
                super.cancelEdit(); // this fires an invalid EditCancelEvent.

                // update the item within this cell, so that it represents the new value
                updateItem(item, false);

                if (table != null) {
                    // reset the editing cell on the TableView
                    table.edit(-1, null);


                }
            }

            super.commitEdit(item);

            setContentDisplay(ContentDisplay.TEXT_ONLY);
        }
    private void createTextField() {
        textField = new TextField(getString());
        textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()
                * 2);

        textField.focusedProperty().addListener(
                new ChangeListener<Boolean>() {
                    @Override
                    public void changed(
                            ObservableValue<? extends Boolean> arg0,
                            Boolean arg1, Boolean arg2) {
                        if (!arg2) {
                            commitEdit((T)textField.getText());
                        }
                    }
                });


        textField.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent t) {
                if (t.getCode() == KeyCode.ENTER) {
                    commitEdit((T)textField.getText());
                } else if (t.getCode() == KeyCode.ESCAPE) {
                    cancelEdit();
                } else if (t.getCode() == KeyCode.TAB) {
                    commitEdit((T)textField.getText());
                    TableColumn nextColumn = getNextColumn(!t.isShiftDown());
                if (nextColumn != null) {
                    getTableView().edit(getTableRow().getIndex(),
                            nextColumn);
                }

                }
                else if (t.getCode() == KeyCode.RIGHT) {
                    commitEdit((T)textField.getText());
                    getTableView().getSelectionModel().selectRightCell();
                    TableColumn nextColumn = getNextColumn(!t.isShiftDown());
                    if (nextColumn != null) {
                        getTableView().edit(getTableRow().getIndex(),
                                nextColumn);
                    }

                    t.consume();
                } else if (t.getCode() == KeyCode.LEFT) {
                    commitEdit((T)textField.getText());
                    getTableView().getSelectionModel().selectLeftCell();
                    TableColumn prevColumn = getNextColumn(false);
                    if (prevColumn != null) {
                        getTableView().edit(getTableRow().getIndex(),
                                prevColumn);
                    }
                    t.consume();
                } else if (t.getCode() == KeyCode.UP) {
                    commitEdit((T)textField.getText());
                    getTableView().getSelectionModel().selectAboveCell();
                    int i=getTableView().getSelectionModel().getSelectedIndex();
                    if(i>=0)
                    getTableView().edit(i,
                            getTableColumn());
                    t.consume();
                } else if (t.getCode() == KeyCode.DOWN) {
                    commitEdit((T)textField.getText());
                    getTableView().getSelectionModel().selectBelowCell();
                    int i=getTableView().getSelectionModel().getSelectedIndex();
                    if(i>=0)
                    getTableView().edit(i,
                            getTableColumn());
                   t.consume();
                }

            }

        });



    }

    private String getString() {
        return getItem() == null ? "" : getItem().toString();
    }

    private TableColumn<S, ?> getNextColumn(boolean forward) {
        List<TableColumn<S, ?>> columns = new ArrayList<>();
        for (TableColumn<S, ?> column : getTableView().getColumns()) {
            columns.addAll(getLeaves(column));
        }
        // There is no other column that supports editing.
        if (columns.size() < 2) {
            return null;
        }
        int currentIndex = columns.indexOf(getTableColumn());
        int nextIndex = currentIndex;
        if (forward) {
            nextIndex++;
            if (nextIndex > columns.size() - 1) {
                nextIndex = 0;
            }
        } else {
            nextIndex--;
            if (nextIndex < 0) {
                nextIndex = columns.size() - 1;
            }
        }
        return columns.get(nextIndex);
    }

    private List<TableColumn<S, ?>> getLeaves(
            TableColumn<S, ?> root) {
        List<TableColumn<S, ?>> columns = new ArrayList<>();
        if (root.getColumns().isEmpty()) {
            // We only want the leaves that are editable.
            if (root.isEditable()) {
                columns.add(root);
            }
            return columns;
        } else {
            for (TableColumn<S, ?> column : root.getColumns()) {
                columns.addAll(getLeaves(column));
            }
            return columns;
        }
    }
}

在我的initialize方法中,我有如下代码

Callback<TableColumn, TableCell> cellFactory = new Callback<TableColumn, TableCell>() {
            public TableCell call(TableColumn p) {
                return new EditingCell();
            }
        };
colName.setCellValueFactory(new PropertyValueFactory<ModelBrBuilding,String>("BranchName"));
        colName.setCellFactory(cellFactory);

        colName.setOnEditCommit(
                new EventHandler<CellEditEvent<ModelBrBuilding, String>>() {
                    @Override
                    public void handle(CellEditEvent<ModelBrBuilding, String> t) {
                        oldName= ((ModelBrBuilding) t.getTableView().getItems().get(
                                t.getTablePosition().getRow())
                                ).getBranchName(); // catch old value before edit

                        ((ModelBrBuilding) t.getTableView().getItems().get(
                                t.getTablePosition().getRow())
                                ).setBranchName(t.getNewValue());
                        newName=t.getNewValue(); // catch new value after edit

                      boolean edit=((ModelBrBuilding) t.getTableView().getItems().get(
                                t.getTablePosition().getRow())
                                ).isEdit();
                             if(edit==false) {
                                 if(oldName!= null  ) 

                                 { 
                        if(!oldName.trim().equals(newName.trim()) && !newName.isEmpty())
                        {


                            ((ModelBrBuilding) t.getTableView().getItems().get(
                                    t.getTablePosition().getRow())
                                    ).setEdit(true);
                        }
                        }
                                 else if(!newName.isEmpty()&& newName != null)
                                    ((ModelBrBuilding) t.getTableView().getItems().get(
                                            t.getTablePosition().getRow())
                                            ).setEdit(true); 
                             }

                    }
                }
            );

这是我在表格顶部添加新行的方法。

public ObservableList<ModelBrBuilding> BuildingData;// contains searched data if there is any in database
//tableBuilding is sorted
// Method for adding new row
@FXML
private void addBuilding() {


        tableBuilding.setEditable(true);
        tableBuilding.getSelectionModel().setCellSelectionEnabled(true);
        colName.setEditable(true);
        //colShortCode.setEditable(true);
        //colActive.setEditable(true);
        if(BuildingData==null)//When search result is empty & there is now row in the table
            {
            tableBuilding.requestFocus();
            tableBuilding.getItems().add(0,new ModelBrBuilding());
            tableBuilding.layout();
            tableBuilding.edit(0, colName);         
            }
    //when search data is not empty 
        else {
        ModelBrBuilding building = new  ModelBrBuilding();

        try {
            BuildingData.add(0,building);
            tableBuilding.layout();
            tableBuilding.edit(0, colName);

            //editBuilding();
        } catch (InstantiationException | IllegalAccessException e) {

            e.printStackTrace();
        }
        }

    }

有人可以在这方面帮助我吗?

1 个答案:

答案 0 :(得分:0)

最后,我已经解决了。添加新行后,我必须刷新表。

@FXML
private void addBuilding() {
    tableBuilding.setEditable(true);
    tableBuilding.getSelectionModel().setCellSelectionEnabled(true);
    colName.setEditable(true);
    //colShortCode.setEditable(true);
    //colActive.setEditable(true);
    if(BuildingData==null)//When search result is empty & there is now row in the table
        {
        tableBuilding.requestFocus();
        tableBuilding.getItems().add(0,new ModelBrBuilding());
        tableBuilding.refresh();
        tableBuilding.layout();
        tableBuilding.edit(0, colName);         
        }
//when search data is not empty 
    else {
    ModelBrBuilding building = new  ModelBrBuilding();

    try {
        BuildingData.add(0,building);
        tableBuilding.refresh();
        tableBuilding.layout();
        tableBuilding.edit(0, colName);

        //editBuilding();
    } catch (InstantiationException | IllegalAccessException e) {

        e.printStackTrace();
    }
    }

}