Search code examples
javajavafxtextfieldhighlight

Highlight all text in TextField upon FIRST click JavaFX


How can I make my text field (JavaFX) exactly the same as the search bar of Google Chrome above. That means, if I click once on it, it marks everything, but if I click again, I am exactly where I clicked.

Example:

Start:

enter image description here

First click:

enter image description here

Click a second time:

enter image description here

EDIT

This is what i tried:

textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
                if (isNowFocused) {
                    textField.selectAll();
                }
                if (wasFocused) {
                    textField.deselect();
                }
            });

But with this code, when I click the first time, everything is selected and gets deselected again immediately.


Solution

  • I would use MouseEvent and EventFilter:

    TextField textField = new TextField("This is a test");
    
    textField.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> {
        if (textField.getSelectedText().equals(textField.getText())) {
            textField.deselect();
        } else if (textField.getSelectedText().isEmpty()) {
            textField.selectAll();
            e.consume();
        } 
    });