JavaFX - Deselect text in TextField when open new stage

Francis M. :

I have designed a simple form with a TextField and a Button.

When the stage is created, with the scene containing the form, the TextField must be preloaded with a character. The problem is that, when the form shows up, the character is selected, as shown in the image.

I tried textfield.deselect() or textfield.positionCaret(1) (or both) but nothing has changed. I don't want to remove the focus on the textfield, but deselect the text and move the caret at the end (so that if the user write something, the first character will not be overwritten).

This is the code I wrote:

try {
        Stage primaryStage = new Stage();
        FXMLLoader loader = new FXMLLoader();
        Pane root = loader.load(getClass().getResource("/resources/view/quick-search.fxml").openStream());
        QuickSearchCtrl quickSearchCtrl = (QuickSearchCtrl) loader.getController();
        quickSearchCtrl.text_tf.setText(text);
        quickSearchCtrl.text_tf.deselect();
        primaryStage.setTitle("");
        primaryStage.setScene(new Scene(root, 230, 54));
        primaryStage.show();
        primaryStage.setResizable(false);
    } catch (IOException e) {
        e.printStackTrace();
    }
gearquicker :

This is an evil crutch, but this work.

quickSearchCtrl.text_tf.setText(text);
deselect(quickSearchCtrl.text_tf);

private void deselect(TextField textField) {
    Platform.runLater(() -> {
        if (textField.getText().length() > 0 &&
                textField.selectionProperty().get().getEnd() == 0) {
            deselect(textField);
        }else{
            textField.selectEnd();
            textField.deselect();
        }
    });
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110035&siteId=1
Recommended