Search code examples
javajavafxbind

How to bind the password field Prompt Text Property to the result of a method in Javafx?


I use the JFXPasswordField and the Label Float 'ON'. So I need to change the prompt while the user is entering the pass according to the input's strength.

I need to bind the property text of a pass field to its strength which is calculated in a function that returns a string as the strength.

Here is the method :

private String getPassStrength() {
    int strength = foo(passwordField.getText());
    if (strength < 4) {
        return "Password is weak";
    } else {
        return "Password is good";
    }
}

And I used different types of bindings such as StringProperty and CreateStringBinding but none worked.

For example :

passwordField.promptTextProperty().bind(Bindings.createStringBinding(this::getPassQuality));

Is there any way to solve this problem?

Edit:

The previous "password" reference was actually the "password field"
The Pass Field input variable was omitted, because I have the reference in the Controller.


Solution

  • You are almost there, I would do it like follows

    password.promptTextProperty().bind(Bindings.createStringBinding(() - > this.getPassStrength(), myPasswordField.textProperty()));
    

    As you noticed I have the password variable which is (I hope) a Label, and a myPasswordField which is a JFXPasswordField.

    The 'promptText' of a (password)textfield is only visible the field is empty. A better name for it would be 'placeholder', as it is meant for a content-information/hint. If you want a popup-message instead, you'l need to implement it yourself (using something like PopupControl or Tooltip).