Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java FX 2 Table Cell Editing and Focus

Tags:

javafx-2

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?

like image 495
wobblycogs Avatar asked Apr 26 '12 10:04

wobblycogs


1 Answers

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

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

and try again.

like image 158
Uluk Biy Avatar answered Sep 30 '22 22:09

Uluk Biy