JPasswordField how to set password

alexj picture alexj · Nov 9, 2012 · Viewed 11.5k times · Source

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);

Answer

Robin picture Robin · Nov 9, 2012

You claim that setText is not working for a JPasswordField is incorrect. See the following piece of code which just works as expected:

  public static void main( String[] args ) {
    EventQueue.invokeLater( new Runnable() {
      @Override
      public void run() {
        JFrame testFrame = new JFrame( "Test" );
        JPasswordField field = new JPasswordField(  );
        field.setColumns( 20 );
        field.setText( "Password" );
        testFrame.add( field );
        testFrame.pack();
        testFrame.setVisible( true );
        testFrame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
      }
    } );
  }

The variant where you pass the text in the constructor (as you did in your code) also works as expected.

So I would search in another direction. The following part

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

makes me wonder whether you see your new JPasswordField in your UI. When you add/remove components from a Container you need to invalidate the layout, as documented in the Container#add and Container#remove methods.

Note: be aware of the security issues when passing the password around as a String. But according to your comments you are already aware of this.