在JavaFX TableView中插入行并开始编辑无法正常工作

时间:2018-03-28 09:38:01

标签: javafx tableview

我们正在运行一个包含一些可编辑表视图的JavaFX应用程序。新请求的功能是:一个按钮,在当前选定的一行下面添加一个新行,并立即开始编辑该行的第一个单元格。

我们实现了这个并不复杂的功能,但我们遇到了一种非常奇怪的行为,经过几天的调查后我们仍然不知道出了什么问题。

当点击按钮时,它会添加一个新行但开始编辑到第一个单元格而不是新创建的行但是在任意其他行上。不幸的是,这个问题不是100%可重现的。有时它按预期工作,但大多数情况下,新添加的行下面的行会被编辑,但有时甚至是在当前所选行之前和之后完全不同的行。

您可以在下面找到可用于查看问题的JavaFX TableView的精简版本的源代码。如前所述,它不是100%可再现的。要查看此问题,您必须多次添加新行。有时,在向上和向下滚动表格时,问题会更频繁发生。

感谢任何帮助。

提示:通过将按钮的动作实现放在runlater()中,我们已经使用了Platform.runlater(),但是虽然问题发生的频率较低,但它从未完全消失。

TableView:

package tableview;

import java.util.ArrayList;
import java.util.List;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Callback;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class SimpleTableViewTest extends Application {

    private final ObservableList<Person> data = FXCollections.observableArrayList(createData());

    private final TableView table = new TableView();

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

    private static List<Person> createData() {
        List<Person> data = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            data.add(new Person("Jacob", "Smith", "jacob.smith_at_example.com", "js_at_example.com"));
        }

        return data;
    }

    @Override
    public void start(Stage stage) {

        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(700);
        stage.setHeight(550);

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

        // Create a customer cell factory so that cells can support editing.
        Callback<TableColumn, TableCell> cellFactory = (TableColumn p) -> {
            return new EditingCell();
        };

        // Set up the columns
        TableColumn firstNameCol = new TableColumn("First Name");
        firstNameCol.setMinWidth(100);
        firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
        firstNameCol.setCellFactory(cellFactory);

        TableColumn lastNameCol = new TableColumn("Last Name");
        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
        lastNameCol.setCellFactory(cellFactory);
        lastNameCol.setEditable(true);

        TableColumn primaryEmailCol = new TableColumn("Primary Email");
        primaryEmailCol.setMinWidth(200);
        primaryEmailCol.setCellValueFactory(new PropertyValueFactory<Person, String>("primaryEmail"));
        primaryEmailCol.setCellFactory(cellFactory);
        primaryEmailCol.setEditable(false);

        TableColumn secondaryEmailCol = new TableColumn("Secondary Email");
        secondaryEmailCol.setMinWidth(200);
        secondaryEmailCol.setCellValueFactory(new PropertyValueFactory<Person, String>("secondaryEmail"));
        secondaryEmailCol.setCellFactory(cellFactory);

        // Add the columns and data to the table.
        table.setItems(data);
        table.getColumns().addAll(firstNameCol, lastNameCol, primaryEmailCol, secondaryEmailCol);
        table.setEditable(true);

        // --- Here comes the interesting part! ---
        //
        // A button that adds a row below the currently selected one
        // and immediatly starts editing it.
        Button addAndEdit = new Button("Add and edit");
        addAndEdit.setOnAction((ActionEvent e) -> {
            int idx = table.getSelectionModel().getSelectedIndex() + 1;

            data.add(idx, new Person());
            table.getSelectionModel().select(idx);
            table.edit(idx, firstNameCol);
        });

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.getChildren().addAll(label, table, addAndEdit);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        ((Group) scene.getRoot()).getChildren().addAll(vbox);

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

}

可编辑的表格单元格:

package tableview;

import javafx.event.EventHandler;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

public class EditingCell extends TableCell<Person, String> {
    private TextField textField;

    public EditingCell() {
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
        setText(getItem());
        setContentDisplay(ContentDisplay.TEXT_ONLY);
    }

    @Override
    public void startEdit() {
        super.startEdit();
        if (textField == null) {
            createTextField();
        }
        setGraphic(textField);
        setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
    }

    @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());
                }
                setGraphic(textField);
                setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            } else {
                setText(getString());
                setContentDisplay(ContentDisplay.TEXT_ONLY);
            }
        }
    }

    private void createTextField() {
        textField = new TextField(getString());
        textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
        textField.setOnKeyPressed(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() {
        return getItem() == null ? "" : getItem().toString();
    }
}

数据Bean:

package tableview;

import javafx.beans.property.SimpleStringProperty;

public class Person {
    private final SimpleStringProperty firstName;
    private final SimpleStringProperty lastName;
    private final SimpleStringProperty primaryEmail;
    private final SimpleStringProperty secondaryEmail;

    public Person() {
        this(null, null, null, null);
    }

    public Person(String firstName, String lastName, String primaryEmail, String secondaryEmail) {
        this.firstName = new SimpleStringProperty(firstName);
        this.lastName = new SimpleStringProperty(lastName);
        this.primaryEmail = new SimpleStringProperty(primaryEmail);
        this.secondaryEmail = new SimpleStringProperty(secondaryEmail);
    }

    public SimpleStringProperty firstNameProperty() {
        return firstName;
    }

    public String getFirstName() {
        return firstName.get();
    }

    public String getLastName() {
        return lastName.get();
    }

    public String getPrimaryEmail() {
        return primaryEmail.get();
    }

    public SimpleStringProperty getPrimaryEmailProperty() {
        return primaryEmail;
    }

    public String getSecondaryEmail() {
        return secondaryEmail.get();
    }

    public SimpleStringProperty getSecondaryEmailProperty() {
        return secondaryEmail;
    }

    public SimpleStringProperty lastNameProperty() {
        return lastName;
    }

    public void setFirstName(String firstName) {
        this.firstName.set(firstName);
    }

    public void setLastName(String lastName) {
        this.lastName.set(lastName);
    }

    public void setPrimaryEmail(String primaryEmail) {
        this.primaryEmail.set(primaryEmail);
    }

    public void setSecondaryEmail(String secondaryEmail) {
        this.secondaryEmail.set(secondaryEmail);
    }
}

1 个答案:

答案 0 :(得分:2)

按钮动作实现的正确代码必须如下所示。解决上述问题的重要方法是'table.layout()'。 非常感谢fabian!

addAndEdit.setOnAction((ActionEvent e) -> {
    int idx = table.getSelectionModel().getSelectedIndex() + 1;

    data.add(idx, new Person());
    table.getSelectionModel().select(idx);

    table.layout();

    table.edit(idx, firstNameCol);
 });