Selecting a word in TextField


Question

The following code is supposed to select a word in a JavaFX TextField:

public class NewFXMain extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        final TextInputControl textField = new TextField("Hello World, World!");

        Button button = new Button("select");
        button.setOnAction(new EventHandler<ActionEvent>() {

            public void handle(ActionEvent t) {
                textField.positionCaret(0);
                textField.selectNextWord();

                System.out.println(textField.getSelectedText());
            }
        });

        VBox root = new VBox();
        root.getChildren().add(textField);
        root.getChildren().add(button);
        primaryStage.setScene(new Scene(root, 300, 100));
        primaryStage.show();
    }
}

It prints Hello in the console, however in the interface nothing is selected (highlighted). If one does the same with a TextArea, the text is correctly selected.

The (wrong) result with a TextField:

enter image description here

And the (correct) result with a TextArea:

enter image description here

What's going on?!?

1
1
2/15/2012 9:06:30 AM

Accepted Answer

TextField doesn't show selection unless it has focus (although I'm not sure is it a bug or a feature). You can see selection by using next code:

    button.setOnAction(new EventHandler<ActionEvent>() {

        public void handle(ActionEvent t) {
            textField.requestFocus(); // get focus first
            textField.positionCaret(0);
            textField.selectNextWord();

            System.out.println(textField.getSelectedText());
        }
    });
5
2/15/2012 12:26:15 PM

The answer to the question is that our understanding of native controls in this regard is that they both clear selection when the text field loses focus and that they (typically) select all text when gaining focus. Our intent with UI controls in JavaFX was to have a native feel but a customized look. Of course, we can have our mind changed on how this works, but it has to be balanced with the goal of maintaining a native feel (which includes select-all on focus gained and not showing selection on focus lost, even if selection exists. But since there is little point to there being any selection on focus lost if it is just going to select-all on focus gained and since weird edge cases will still exist as a result, we have to wonder whether it is worth changing this).


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon