Josh Narsu
Josh Narsu

Reputation: 59

Highlight all text in TextField upon click JavaFX

I'm making a JavaFX application and upon launch, the TextField has default text that says "Please enter this value", the user is supposed to delete said text and enter a value. However, it is quite a pain to click, drag, and highlight all the text each time. Is there a way to make it so when the user clicks on the TextField, it automatically highlights all the text for easy deletion, but ONLY when the text is equal to the default message? I researched this and couldn't find anything, any help would be much appreciated.

Upvotes: 2

Views: 5771

Answers (2)

Isaac Vu
Isaac Vu

Reputation: 21

This line works fine for me

textField.setOnMouseClicked(e -> textField.selectAll());

Upvotes: 2

James_D
James_D

Reputation: 209684

To do what you explicitly ask, you can use

textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
    if (isNowFocused && DEFAULT_TEXT.equals(textField.getText())) {
        textField.selectAll();
    }
});

But it is probably better to use promptText for this functionality anyway:

textField.setPromptText(DEFAULT_TEXT);

Upvotes: 7

Related Questions