TableView不会在焦点丢失事件上提交值

时间:2015-04-11 10:04:46

标签: javafx tableview

我想创建一个包含以下功能的表格:

  • 按键编辑
  • 输入键=下一行
  • Tab键=下一栏
  • 退出键=取消修改

以下是实现这些功能的代码。值应该在焦点丢失时提交。问题:他们没有承诺。触发焦点更改事件,根据控制台输出值将是正确的,但最后表格单元格中的值是旧的。

有谁知道如何防止这种情况以及如何获取当前的EditingCell对象以便我可以手动调用提交?毕竟应该调用某种验证器,如果值不正确,则会阻止更改焦点。

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TablePosition;
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.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Callback;

public class TableViewInlineEditDemo extends Application {

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

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setWidth(450);
        stage.setHeight(550);

        final Label label = new Label("Address Book");
        label.setFont(new Font("Arial", 20));

        table.setEditable(true);

        Callback<TableColumn<Person, String>, TableCell<Person, String>> cellFactory = (TableColumn<Person, String> p) -> new EditingCell();

        TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
        TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
        TableColumn<Person, String> emailCol = new TableColumn<>("Email");

        firstNameCol.setMinWidth(100);
        firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
        firstNameCol.setCellFactory(cellFactory);
        firstNameCol.setOnEditCommit((CellEditEvent<Person, String> t) -> {
            ((Person) t.getTableView().getItems().get(t.getTablePosition().getRow())).setFirstName(t.getNewValue());
        });

        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
        lastNameCol.setCellFactory(cellFactory);
        lastNameCol.setOnEditCommit((CellEditEvent<Person, String> t) -> {
            ((Person) t.getTableView().getItems().get(t.getTablePosition().getRow())).setLastName(t.getNewValue());
        });

        emailCol.setMinWidth(200);
        emailCol.setCellValueFactory(new PropertyValueFactory<>("email"));
        emailCol.setCellFactory(cellFactory);
        emailCol.setOnEditCommit((CellEditEvent<Person, String> t) -> {
            ((Person) t.getTableView().getItems().get(t.getTablePosition().getRow())).setEmail(t.getNewValue());
        });

        table.setItems(data);
        table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);


        // edit mode on keypress
        table.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent e) {

                if( e.getCode() == KeyCode.TAB) { // commit should be performed implicitly via focusedProperty, but isn't
                    table.getSelectionModel().selectNext();
                    e.consume();
                    return;
                }
                else if( e.getCode() == KeyCode.ENTER) { // commit should be performed implicitly via focusedProperty, but isn't
                    table.getSelectionModel().selectBelowCell();
                    e.consume();
                    return;
                }

                // switch to edit mode on keypress, but only if we aren't already in edit mode
                if( table.getEditingCell() == null) {
                    if( e.getCode().isLetterKey() || e.getCode().isDigitKey()) {  

                        TablePosition focusedCellPosition = table.getFocusModel().getFocusedCell();
                        table.edit(focusedCellPosition.getRow(), focusedCellPosition.getTableColumn());

                    }
                }

            }
        });

        // single cell selection mode
        table.getSelectionModel().setCellSelectionEnabled(true);
        table.getSelectionModel().selectFirst();


        final VBox vbox = new VBox();
        vbox.getChildren().addAll(label, table);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();
    }


    class EditingCell extends TableCell<Person, String> {

        private TextField textField;

        public EditingCell() {
        }

        @Override
        public void startEdit() {
            if (!isEmpty()) {
                super.startEdit();
                createTextField();
                setText(null);
                setGraphic(textField);
                textField.requestFocus(); // must be before selectAll() or the caret would be in wrong position
                textField.selectAll();
            } 
        }

        @Override
        public void cancelEdit() {
            super.cancelEdit();
            setText((String) getItem());
            setGraphic(null);
        }

        @Override
        public void updateItem(String item, boolean empty) {
            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() {

            textField = new TextField(getString());
            textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);

            // commit on focus lost
            textField.focusedProperty().addListener((ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {

                if( oldValue = true && newValue == false) {

                    System.out.println( "Focus lost, current value: " + textField.getText());

                    commitEdit();

                }
            });

            // cancel edit on ESC
            textField.addEventFilter(KeyEvent.KEY_RELEASED, e -> {

                if( e.getCode() == KeyCode.ESCAPE) {
                    cancelEdit();
                }

            });

        }

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

        private boolean commitEdit() {
            super.commitEdit(textField.getText());
            return true; // TODO: add verifier and check if commit was possible
        }
    }

    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;
        private final SimpleStringProperty email;

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

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

}

非常感谢!

编辑:我已将其缩小范围。似乎问题是当焦点改变时,JavaFX代码取消编辑模式。那太糟糕了。

public Cell() {
    setText(null); // default to null text, to match the null item
    // focusTraversable is styleable through css. Calling setFocusTraversable
    // makes it look to css like the user set the value and css will not 
    // override. Initializing focusTraversable by calling set on the 
    // CssMetaData ensures that css will be able to override the value.
    ((StyleableProperty<Boolean>)(WritableValue<Boolean>)focusTraversableProperty()).applyStyle(null, Boolean.FALSE);
    getStyleClass().addAll(DEFAULT_STYLE_CLASS);

    /**
     * Indicates whether or not this cell has focus. For example, a
     * ListView defines zero or one cell as being the "focused" cell. This cell
     * would have focused set to true.
     */
    super.focusedProperty().addListener(new InvalidationListener() {
        @Override public void invalidated(Observable property) {
            pseudoClassStateChanged(PSEUDO_CLASS_FOCUSED, isFocused()); // TODO is this necessary??

            // The user has shifted focus, so we should cancel the editing on this cell
            if (!isFocused() && isEditing()) {
                cancelEdit();
            }
        }
    });

    // initialize default pseudo-class state
    pseudoClassStateChanged(PSEUDO_CLASS_EMPTY, true);
}

4 个答案:

答案 0 :(得分:13)

我很好奇并做了一些背景研究。

您正面临着JavaFX中众所周知的错误问题。

<强> 背景

当您致电commitEdit(textField.getText())时,它首先要检查isEditing()的值,如果值为false则返回,而不提交。

public void commitEdit(T newValue) {
    if (! isEditing()) return;

    ... // Rest of the things
}

为什么会返回false?

您可能已经发现,只要您按TABENTER更改选择,就会调用cancelEdit()TableCell.isEditing()设置为false。当调用textField的焦点属性侦听器中的commitEdit()时,isEditing()已经返回 false

解决方案/黑客

JavaFX社区的主题一直在讨论。那里的人发布了 hacks ,欢迎您查看。

a SO thread中有一个黑客攻击,似乎完成了工作,虽然我还没有尝试过(但是)。

答案 1 :(得分:2)

我解决这个暴行的建议如下(抱歉缺少JavaDoc)。

这是一个取消提交重定向解决方案。我使用Java 1.8.0-121在LINUX下测试它。在这里,如何丢弃单元格编辑器的唯一方法是按ESCAPE。

import javafx.beans.binding.Bindings;
import javafx.scene.Node;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

public abstract class AutoCommitTableCell<S,T> extends TableCell<S,T>
{
    private Node field;
    private boolean startEditing;
    private T defaultValue;


    /** @return a newly created input field. */
    protected abstract Node newInputField();

    /** @return the current value of the input field. */
    protected abstract T getInputValue();

    /** Sets given value to the input field. */
    protected abstract void setInputValue(T value);

    /** @return the default in case item is null, must be never null, else cell will not be editable. */
    protected abstract T getDefaultValue();

    /** @return converts the given value to a string, being the cell-renderer representation. */
    protected abstract String inputValueToText(T value);


    @Override
    public void startEdit() {
        try {
            startEditing = true;

            super.startEdit();  // updateItem() will be called

            setInputValue(getItem());
        }
        finally {
            startEditing = false;
        }
    }

    /** Redirects to commitEdit(). Leaving the cell should commit, just ESCAPE should cancel. */
    @Override
    public void cancelEdit() {
        // avoid JavaFX NullPointerException when calling commitEdit()
        getTableView().edit(getIndex(), getTableColumn());

        commitEdit(getInputValue());
    }

    private void cancelOnEscape() {
        if (defaultValue != null)    {   // canceling default means writing null
            setItem(defaultValue = null);
            setText(null);
            setInputValue(null);
        }
        super.cancelEdit();
    }

    @Override
    protected void updateItem(T newValue, boolean empty) {
        if (startEditing && newValue == null)
            newValue = (defaultValue = getDefaultValue());

        super.updateItem(newValue, empty);

        if (empty || newValue == null) {
            setText(null);
            setGraphic(null);
        }
        else {
            setText(inputValueToText(newValue));
            setGraphic(startEditing || isEditing() ? getInputField() : null);
        }
    }

    protected final Node getInputField()    {
        if (field == null)    {
            field = newInputField();

            // a cell-editor won't be committed or canceled automatically by JFX
            field.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
                if (event.getCode() == KeyCode.ENTER || event.getCode() == KeyCode.TAB)
                    commitEdit(getInputValue());
                else if (event.getCode() == KeyCode.ESCAPE)
                    cancelOnEscape();
            });

            contentDisplayProperty().bind(
                    Bindings.when(editingProperty())
                        .then(ContentDisplay.GRAPHIC_ONLY)
                        .otherwise(ContentDisplay.TEXT_ONLY)
                );
        }
        return field;
    }
}

您可以扩展此类以支持任何数据类型。

String字段的示例是( Person 是一个示例bean):

import javafx.scene.Node;
import javafx.scene.control.TextField;
import jfx.examples.tablebinding.PersonsModel.Person;

public class StringTableCell extends AutoCommitTableCell<Person,String>
{
    @Override
    protected String getInputValue() {
        return ((TextField) getInputField()).getText();
    }

    @Override
    protected void setInputValue(String value) {
        ((TextField) getInputField()).setText(value);
    }

    @Override
    protected String getDefaultValue() {
        return "";
    }

    @Override
    protected Node newInputField() {
        return new TextField();
    }

   @Override
    protected String inputValueToText(String newValue) {
        return newValue;
    }
}

以这种方式应用:

final TableColumn<Person,String> nameColumn = new TableColumn<Person,String>("Name");
nameColumn.setCellValueFactory(
        cellDataFeatures -> cellDataFeatures.getValue().nameProperty());
nameColumn.setCellFactory(
        cellDataFeatures -> new StringTableCell());

答案 2 :(得分:2)

我遇到了同样的问题,我通过组合这两个代码片段解决了这个问题:

自定义TableCell实施

public class EditCell<S, T> extends TableCell<S, T> {
    private final TextField textField = new TextField();

    // Converter for converting the text in the text field to the user type, and vice-versa:
    private final StringConverter<T> converter;

    /**
     * Creates and initializes an edit cell object.
     * 
     * @param converter
     *            the converter to convert from and to strings
     */
    public EditCell(StringConverter<T> converter) {
        this.converter = converter;

        itemProperty().addListener((obx, oldItem, newItem) -> {
            setText(newItem != null ? this.converter.toString(newItem) : null);
        });

        setGraphic(this.textField);
        setContentDisplay(ContentDisplay.TEXT_ONLY);

        this.textField.setOnAction(evt -> {
            commitEdit(this.converter.fromString(this.textField.getText()));
        });
        this.textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
            if (!isNowFocused) {
                commitEdit(this.converter.fromString(this.textField.getText()));
            }
        });
        this.textField.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
            if (event.getCode() == KeyCode.ESCAPE) {
                this.textField.setText(this.converter.toString(getItem()));
                cancelEdit();
                event.consume();
            } else if (event.getCode() == KeyCode.TAB) {
                commitEdit(this.converter.fromString(this.textField.getText()));
                TableColumn<S, ?> nextColumn = getNextColumn(!event.isShiftDown());
                if (nextColumn != null) {
                    getTableView().getSelectionModel().clearAndSelect(getTableRow().getIndex(), nextColumn);
                    getTableView().edit(getTableRow().getIndex(), nextColumn);
                }
            }
        });
    }

    /**
     * Convenience converter that does nothing (converts Strings to themselves and vice-versa...).
     */
    public static final StringConverter<String> IDENTITY_CONVERTER = new StringConverter<String>() {

        @Override
        public String toString(String object) {
            return object;
        }

        @Override
        public String fromString(String string) {
            return string;
        }

    };

    /**
     * Convenience method for creating an EditCell for a String value.
     * 
     * @return the edit cell
     */
    public static <S> EditCell<S, String> createStringEditCell() {
        return new EditCell<S, String>(IDENTITY_CONVERTER);
    }

    // set the text of the text field and display the graphic
    @Override
    public void startEdit() {
        super.startEdit();
        this.textField.setText(this.converter.toString(getItem()));
        setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
        this.textField.requestFocus();
    }

    // revert to text display
    @Override
    public void cancelEdit() {
        super.cancelEdit();
        setContentDisplay(ContentDisplay.TEXT_ONLY);
    }

    // commits the edit. Update property if possible and revert to text display
    @Override
    public void commitEdit(T item) {
        // This block is necessary to support commit on losing focus, because the baked-in mechanism
        // sets our editing state to false before we can intercept the loss of focus.
        // The default commitEdit(...) method simply bails if we are not editing...
        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.commitEdit(item);

        setContentDisplay(ContentDisplay.TEXT_ONLY);
    }

    /**
     * Finds and returns the next editable column.
     * 
     * @param forward
     *            indicates whether to search forward or backward from the current column
     * @return the next editable column or {@code null} if there is no next column available
     */
    private TableColumn<S, ?> getNextColumn(boolean forward) {
        List<TableColumn<S, ?>> columns = new ArrayList<>();
        for (TableColumn<S, ?> column : getTableView().getColumns()) {
            columns.addAll(getEditableColumns(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);
    }

    /**
     * Returns all editable columns of a table column (supports nested columns).
     * 
     * @param root
     *            the table column to check for editable columns
     * @return a list of table columns which are editable
     */
    private List<TableColumn<S, ?>> getEditableColumns(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(getEditableColumns(column));
            }
            return columns;
        }
    }
}

<强>控制器

    @FXML
    private void initialize() {
        table.getSelectionModel().setCellSelectionEnabled(true);
        table.setEditable(true);

        table.getColumns().add(createColumn("First Name", Person::firstNameProperty));
        table.getColumns().add(createColumn("Last Name", Person::lastNameProperty));
        table.getColumns().add(createColumn("Email", Person::emailProperty));

        table.getItems().addAll(
                new Person("Jacob", "Smith", "jacob.smith@example.com"),
                new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
                new Person("Ethan", "Williams", "ethan.williams@example.com"),
                new Person("Emma", "Jones", "emma.jones@example.com"),
                new Person("Michael", "Brown", "michael.brown@example.com")
        );

        table.setOnKeyPressed(event -> {
            TablePosition<Person, ?> pos = table.getFocusModel().getFocusedCell() ;
            if (pos != null && event.getCode().isLetterKey()) {
                table.edit(pos.getRow(), pos.getTableColumn());
            }
        });
    }

    private <T> TableColumn<T, String> createColumn(String title, Function<T, StringProperty> property) {
        TableColumn<T, String> col = new TableColumn<>(title);
        col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));

        col.setCellFactory(column -> EditCell.createStringEditCell());
        return col;
    }

答案 3 :(得分:0)

我找到了一个简单的解决方案,适用于我的TableCells。这个想法是忘记了焦点丢失时的commitEdit。让javafx完成它的工作,然后只更新以前编辑过的单元格的值。

abstract class EditingTextCell<T, V> extends TableCell<T, V> {
    protected TextField textField;
    private T editedItem;

    @Override
    public void startEdit() {
        ...
        textField.focusedProperty().addListener((t, oldval, newval) -> {
            if (!newval) {
                setItemValue(editedItem, textField.getText());
            }
        });

        editedItem = (T) getTableRow().getItem();
    }
    public abstract void setItemValue(T item, String text);
    ...
}

所以,唯一的技巧是以更新项目的正确部分的方式实现setItemValue()。