JOptionPane to get password

Ahamed picture Ahamed · Jan 16, 2012 · Viewed 62.6k times · Source

JOptionPane can be used to get string inputs from user, but in my case, I want to display a password field in showInputDialog.

The way I need is the input given by the user should be masked and the return value must be in char[]. I need a dialog box with a message, password field, and two buttons. Can that be done? Thanks.

Answer

Eng.Fouad picture Eng.Fouad · Jan 16, 2012

Yes, it is possible using JOptionPane.showOptionDialog(). Something like this:

JPanel panel = new JPanel();
JLabel label = new JLabel("Enter a password:");
JPasswordField pass = new JPasswordField(10);
panel.add(label);
panel.add(pass);
String[] options = new String[]{"OK", "Cancel"};
int option = JOptionPane.showOptionDialog(null, panel, "The title",
                         JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE,
                         null, options, options[1]);
if(option == 0) // pressing OK button
{
    char[] password = pass.getPassword();
    System.out.println("Your password is: " + new String(password));
}