Selecting a word in TextField

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() {

            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?!?

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() {

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

            System.out.println(textField.getSelectedText());
        }
    });
Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Selecting a word in TextField

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录