javaswinguser-interfacepasswordsjoptionpane

JOptionPane to get password


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.


Solution

  • 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[0]);
    if(option == 0) // pressing OK button
    {
        char[] password = pass.getPassword();
        System.out.println("Your password is: " + new String(password));
    }