6

I've been learning a bit about JavaFX 2 but I've hit a problem with editable table cells that I can't find a solution too. To save pasting in a lot of code I've created a project that contains only the TableView example from the JavaFX documentation: http://docs.oracle.com/javafx/2/ui_controls/table-view.htm

If you run up this code you see this behaviour:

  1. Clicking a row selects that row.
  2. Clicking a cell in the selected row converts the cell to a text field so that it is ready to be edited.
  3. Clicking in the text field allows the contents to be edited.

The problem is that's three clicks to get to the point where the cell can be edited. What I would like to achieve is when the text field in created (e.g. step 2) focus switches to the text field directly.

My best guess regarding how to achieve this was to add textField.requestFocus() to the end of the the startEditing() method:

@Override
public void startEdit() {
    super.startEdit();

    if (textField == null) {
        createTextField();
    }
    setGraphic(textField);
    setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
    textField.selectAll();
    textField.requestFocus();
}

but this doesn't work. If I add a focus listener to the text field what I find is that it gets focus but then looses it again. Sticking a break point in the listener seems to indicate that the TableView is taking focus back before the text field is displayed.

The question therefore is how do I give focus to the text field when editing starts?

wobblycogs
  • 4,083
  • 7
  • 37
  • 48

1 Answers1

8

Could you please replace the line textField.requestFocus(); with:

      Platform.runLater(new Runnable() {
            @Override
            public void run() {
                textField.requestFocus();
            }
       });

and try again.

Uluk Biy
  • 48,655
  • 13
  • 146
  • 153
  • 1
    Thanks Uluk, that's fixed it. Looking at the documentation for runLater though I'm guessing this could fail as it doesn't make any guarantee about when it will run - presumably it could run before the table grabs focus back. – wobblycogs Apr 26 '12 at 11:02
  • I agree with wobblycogs, I've used the runlater trick to request focus a few times in the past and it has always worked for me, but a lack of certainty that it would continue to work doesn't give me a warm, fuzzy feeling about it. (An alternative is to use a Timeline to push the focus request back even later - but that approach has it's own issues). – jewelsea Apr 26 '12 at 18:10