Search code examples
javaswingpasswordsjpasswordfield

JPasswordField how to set password


Hello I am using a JPasswordField when I want to read it it is no problem with getPassword but what I am doing is when the Password is not set it shows a InputDialog where you can type in the password and then it should set the the Password in to the JPasswordField but when I use setText it does not set it and there is not method setPassword(). So my question is how can i set a password to a JPasswordField?

String password = "";
JPasswordField passwordField = new JPasswordField();
passwordField.setEchoChar('*');
Object[] obj = {"Bitte ihr PAsswort eingeben:\n\n", passwordField};
Object stringArray[] = {"OK","Cancel"};

if (JOptionPane.showOptionDialog(null, obj, "Passwort", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray, obj) == JOptionPane.WARNING_MESSAGE)
{
password = new String(passwordField.getPassword());
}

txtFtpUser.setText(username);
panel_1.remove(txtFtpPassword);
txtFtpPassword = new JPasswordField(password);
txtFtpPassword.setBounds(10, 113, 206, 23);
panel_1.add(txtFtpPassword);

Solution

  • I found the Error here it was:

    if (JOptionPane.showOptionDialog(null, obj, "Passwort", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray, obj) == JOptionPane.WARNING_MESSAGE)
    {
    password = new String(passwordField.getPassword());
    }
    

    It checked it was a Warning Message but it was a YES_OPTION :) Thank you for all your help.