bazi
bazi

Reputation: 1876

javafx how to request focus on the table cell?

I have a editable TableView which validates the input on the tablecells. If user types invalid input then an alert box will be shown with the error message. however when the alert box is shown, the TableCell and the TableView loses focus. The code below describes the scenario.

tableColumn.setOnEditCommit(evt -> {
    boolean inputValid = // do validation;
    if(!inputValid) {
        int row = tableView.getEditingCell().getRow();
        Alert alert = new Alert(AlertType.ERROR);
        alert.setContentText("Invalid input");
        alert.initModality(Modality.WINDOW_MODAL);
        alert.initOwner(tableView.getScene().getWindow());
        alert.showAndWait();
        tableView.requestFocus(); // get back focus
        tableView.edit(row, tableColumn);
    }
});

this grabs the focus back to the TableView after showing the alert box but the TextField inside the TableCell does not have focus. how to accomplish this? and by the way, im using the EditingCell TableCell instead of the TextFieldTableCell.

Upvotes: 3

Views: 4878

Answers (2)

Petr Pahorecký
Petr Pahorecký

Reputation: 23

I use:

    tableview.getFocusModel().focus(row, tableColumn);
    tableview.requestFocus();

It works for me.

Upvotes: 1

7twenty7
7twenty7

Reputation: 568

Try:

You need to define a TablePosition:

Example: TablePosition pos = new TablePosition(tableView, 0, null);

Set the focus to it:

tableView.getFocusModel().focus(pos);

Upvotes: 1

Related Questions