Yonex
Yonex

Reputation: 124

Enable edit only for the selected row in the table

I am fairly new in JavaFX. I have a table with multiple columns and an Edit button in each row. Whenever I click on the Edit 1st cell is selected for edit of that row. Everything goes fine but the problem is whenever I select a row and click on a cell of it also gets in edit mode though I have not clicked Edit. I think it's because I have made tableView.setEditable(true) but I want to enable edit only when I click Edit button and only for that row, not others when I double click/ single click. I have seen this but they have solved it by a pop-up. I don't want that. In the initialize() method I tried this way but it's not working exactly. Can anyone show me the correct way to do this, please?

tableBuilding.setRowFactory(tv -> {
                TableRow<ModelBrBuilding> row = new TableRow<>();
                row.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> {
                    if (e.getButton() == MouseButton.SECONDARY) {
                        e.consume();
                    }
                });

               row.addEventFilter(MouseEvent.MOUSE_PRESSED,event -> {
                if ( event.getButton() == MouseButton.PRIMARY   && event.getClickCount() == 2  ) {
                    event.consume();
                }
                });
                return row ;
            });

and my button action looks like

 EditButton.setOnAction((ActionEvent event)->{                  
                    TableRow row = cell.getTableRow();
                    tableBuilding.requestFocus();
                    tableBuilding.getSelectionModel().select(row.getIndex());            
                        int i=tableBuilding.getSelectionModel().getSelectedIndex();
                        tableBuilding.edit(i,colName);                                                          
                });

Upvotes: 0

Views: 1385

Answers (1)

Slaw
Slaw

Reputation: 45806

There may be a more elegant solution to this, but you could simply set the TableView editable right before you call tableView.edit(int, TableColumn) and then set it back to not being editable when the edit is either committed or cancelled. Or you can do this set\unset editable thing on each specific TableColumn.

For instance, in your Button's action handler:

button.setOnAction(evt -> {
    evt.consume();
    tableView.requestFocus();
    tableView.edit(-1, null); // cancel any current edit if there is one
    tableView.getSelectionModel().select(tableCell.getIndex());
    tableView.setEditable(true);
    tableView.edit(tableCell.getIndex(), tableColumn);
});

And then for the TableColumn:

EventHandler<TableColumn.CellEditEvent<S, T>> handler = evt -> tableView.setEditable(false);
tableColumn.setOnEditCancel(handler);
tableColumn.setOnEditCommit(handler);
// or you can use the addEventHandler(EventType, EventHandler) method

Upvotes: 1

Related Questions