TableView переходит к последней ячейке строки после редактирования коммита при использовании экстрактора для TableView ObservableList - PullRequest
2 голосов
/ 04 мая 2020

У меня есть TableView типа Bean, который состоит из столбцов имени, количества, цены и общей цены. Эти столбцы можно изменять с помощью TextFieldTableCell, за исключением общего столбца, который отвечает за представление общей стоимости каждой строки. Кроме того, я определил экстрактор для наблюдения за изменениями цены и количества. Вот некоторый фрагмент кода:

public void start(Stage primaryStage) {
        TableView<Bean> table = new TableView<>();
        table.setEditable(true);
        table.getSelectionModel().setCellSelectionEnabled(true);

        TableColumn<Bean, String> nameColumn = new TableColumn<>("name");
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        nameColumn.setOnEditCommit(e -> {
            Bean bean = e.getRowValue();
            bean.setName(e.getNewValue());
        });

        TableColumn<Bean, Integer> quantityColumn = new TableColumn<>("quantity");
        quantityColumn.setCellValueFactory(new PropertyValueFactory<>("quantity"));
        quantityColumn.setCellFactory(TextFieldTableCell.forTableColumn(new StringConverter<>() {
            @Override
            public String toString(Integer object) {
                return object.toString();
            }

            @Override
            public Integer fromString(String string) {
                return Integer.parseInt(string);
            }
        }));
        quantityColumn.setOnEditCommit(e -> {
            Bean bean = e.getRowValue();
            bean.setQuantity(e.getNewValue());
        });

        TableColumn<Bean, Integer> priceColumn = new TableColumn<>("price");
        priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
        priceColumn.setCellFactory(TextFieldTableCell.forTableColumn(new StringConverter<>() {
            @Override
            public String toString(Integer object) {
                return object.toString();
            }

            @Override
            public Integer fromString(String string) {
                return Integer.parseInt(string);
            }
        }));
        quantityColumn.setOnEditCommit(e -> {
            Bean bean = e.getRowValue();
            bean.setQuantity(e.getNewValue());
        });

        TableColumn<Bean, Integer> totalColumn = new TableColumn<>("total");
        totalColumn.setCellValueFactory(new PropertyValueFactory<>("totalPrice"));

        table.getColumns().addAll(nameColumn, priceColumn, quantityColumn, totalColumn);

        ObservableList<Bean> list = FXCollections.observableArrayList(bean -> new Observable[]{bean.priceProperty(), bean.quantityProperty()});
        list.add(new Bean("Tomato", 20, 100));
        list.add(new Bean("Orange", 10, 200));

        table.setItems(list);

        BorderPane pane = new BorderPane();
        pane.setCenter(table);

        Scene scene = new Scene(pane);
        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();
    }



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

public class Bean {
    private SimpleStringProperty name;
    private SimpleIntegerProperty quantity;
    private SimpleIntegerProperty price;
    private SimpleIntegerProperty totalPrice;

    Bean(String name, Integer quantity, Integer price) {
        this.name = new SimpleStringProperty(name);
        this.quantity = new SimpleIntegerProperty(quantity);
        this.price = new SimpleIntegerProperty(price);
        this.totalPrice = new SimpleIntegerProperty(0);
        this.totalPrice.bind(Bindings.createIntegerBinding(() -> {
            return getQuantity() * getPrice();
        }, quantityProperty(), priceProperty()));
    }

    public String getName() {
        return this.name.get();
    }

    public void setName(String name) {
        this.name.set(name);
    }

    public Integer getQuantity() {
        return this.quantity.get();
    }

    public void setQuantity(Integer quantity) {
        this.quantity.set(quantity);
    }

    public SimpleIntegerProperty quantityProperty() {
        return this.quantity;
    }

    public Integer getPrice() {
        return this.price.get();
    }

    public void setPrice(Integer price) {
        this.price.set(price);
    }

    public SimpleIntegerProperty priceProperty() {
        return this.price;
    }

    public Integer getTotalPrice() {
        return this.totalPrice.get();
    }

    public void setTotalPrice(Integer totalPrice) {
        this.totalPrice.set(totalPrice);
    }
}

Проблема заключается в том, что каждый раз, когда я устанавливаю экстрактор для ObservableList, TableView переходит к последней ячейке текущей строки после фиксации столбца цены или количества.

...