Java FX 2 Table Cell Editing and Focus

做~自己de王妃 提交于 2020-01-03 09:07:12

问题


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?


回答1:


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

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

and try again.



来源:https://stackoverflow.com/questions/10331497/java-fx-2-table-cell-editing-and-focus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!