JavaFx: Method selectAll() just works by focus with keyboard
Asked Answered
K

2

10

i use selectionAll() to select the whole text in my textfield but it just works when the focus comes from keyboard (like Tab).

If i click with my mouse in the textfield, it selects the text just for a very short moment. But it has to work like with the focus which comes from the keyboard.

flaschenPreis.focusedProperty().addListener(new ChangeListener<Boolean>() {
    public void changed(ObservableValue ov, Boolean t, Boolean t1) {

        if ( flaschenPreis.isFocused() && !flaschenPreis.getText().isEmpty()) {
            flaschenPreis.selectAll();
        }              
    }
});


literPreis.focusedProperty().addListener(new ChangeListener() {
    public void changed(ObservableValue ov, Object t, Object t1) {

        if (literPreis.isFocused() && !literPreis.getText().isEmpty()) {
            literPreis.selectAll();
        }
    }
});

flaschenPreis und literPreis are my textfields

Kreda answered 19/2, 2013 at 19:0 Comment(1)
it looks like a bug ,please report here javafx-jira.kenai.com/secure/Dashboard.jspaHomogeny
G
23

This trick will help you :

final TextField tf = new TextField("Text");
tf.focusedProperty().addListener(new ChangeListener<Boolean>() {
    @Override
    public void changed(ObservableValue ov, Boolean t, Boolean t1) {

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                if (tf.isFocused() && !tf.getText().isEmpty()) {
                    tf.selectAll();
                }
            }
        });
    }
});
Guizot answered 19/2, 2013 at 20:40 Comment(4)
Wow! It works!! Awesome!!! This part is so important for the programm im working on. Thank you so much!! I really appreciate your help.Kreda
Sonja, did you file an issue about that?Guizot
We're over 5 years and a few Java(FX) releases further, but the problem seems to be still in (using Java 8u172 and related JavaFX)... Has the issue been filed?Bucher
Nice. Platform.runLater() solved the problem. Thank you.Czar
C
2

This worked for me:

PathField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
    if (isNowFocused) {
        Platform.runLater(() -> PathField.selectAll());
    }
});
Colman answered 21/7, 2019 at 22:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.