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:
First click:
Click a second time:
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.
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();
}
});