DarthRitis
DarthRitis

Reputation: 382

JavaFX - How to refer to a cell's neighbor in tableview

I'm working on creating a table in JavaFX that contains editable properties. I want to be able to start editing, commit changes, and cancel with buttons that will be included in each row; however, I'm having some difficulty referring to the cell that I want to start editing. Ideally, I'd like to do something similar to this:

controller.buttonColumn.setCellFactory(p -> new TableCell<TableItem, String>(){
            @Override
            protected void updateItem(String s, boolean empty) {
                super.updateItem(s, empty);
                if (getTableRow().getItem()==null){
                    setGraphic(null);
                    return;
                }
                Button editButton = new Button("Edit");
                editButton.setOnAction(event -> {
                    getTableRow().getCell(1).startEdit();
                });
                setGraphic(editButton);

        });

This doesn't work though because TableRow does not have a method to access specific cells. Similarly, I could use a line like this:

getTableView().getEditingCell().cancelEdit();

for my cancel button, but the getEditingCell() method does not return a TableCell but a TablePosition, which does not have a method to access the corresponding cell.

tl;dr I'm looking for a way to access a cell in TableView given it's neighbor.

Upvotes: 1

Views: 307

Answers (1)

James_D
James_D

Reputation: 209684

You can use the TableView.edit(int row, TableColumn<S,?> column) method:

controller.buttonColumn.setCellFactory(p -> new TableCell<TableItem, String>(){
    @Override
    protected void updateItem(String s, boolean empty) {
        super.updateItem(s, empty);
        if (getTableRow().getItem()==null){
            setGraphic(null);
            return;
        }
        Button editButton = new Button("Edit");
        editButton.setOnAction(event -> {
            getTableView().edit(getIndex(), someTableColumn);
        });
        setGraphic(editButton);
    }
});

where someTableColumn is the column containing the cell you want to start editing.

You can use the same method to cancel editing:

tableView.edit(-1, null);

Upvotes: 1

Related Questions