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:

And the (correct) result with a TextArea:

What’s going on?!?
TextFielddoesn’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: