How to unmask a JavaFX PasswordField or properly mask a TextField?

后端 未结 5 952
孤街浪徒
孤街浪徒 2020-11-29 11:19

In a UI of mine, I have a PasswordField like so (urm the one at the bottom!):

\"Login

5条回答
  •  醉话见心
    2020-11-29 11:40

    You need create three elements:

    • TextField : the password visible field
    • PasswodField : the password not visible field
    • CheckBox : the toggle visibility field

    You place the passwords fields in the same position(x, y):

    
    
    
    

    Note: Replaces the value of X and Y.

    Add in your controller:

    @FXML
    private TextField pass_text;
    @FXML
    private CheckBox pass_toggle;
    @FXML
    private Button btn_start_stop;
    
    /**
     * Controls the visibility of the Password field
     * @param event
     */
    @FXML
    public void togglevisiblePassword(ActionEvent event) {
        if (pass_toggle.isSelected()) {
            pass_text.setText(pass_hidden.getText());
            pass_text.setVisible(true);
            pass_hidden.setVisible(false);
            return;
        }
        pass_hidden.setText(pass_text.getText());
        pass_hidden.setVisible(true);
        pass_text.setVisible(false);
    }
    
    //Run
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        this.togglevisiblePassword(null);
    }
    

    If you want to know the value of the password you can create a method that returns it:

    private String passwordValue() {
        return pass_toggle.isSelected()?
           pass_text.getText(): pass_hidden.getText();
    }
    

提交回复
热议问题