JOptionPane to get password
The easiest thing is to use JOptionPane
's showConfirmDialog
method and to pass in a reference to a JPasswordField
; e.g.
JPasswordField pf = new JPasswordField();
int okCxl = JOptionPane.showConfirmDialog(null, pf, "Enter Password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (okCxl == JOptionPane.OK_OPTION) {
String password = new String(pf.getPassword());
System.err.println("You entered: " + password);
}
Edit
Below is an example using a custom JPanel
to display a message along with the JPasswordField
. Per the most recent comment, I've also (hastily) added code to allow the JPasswordField
to gain focus when the dialog is first displayed.
public class PasswordPanel extends JPanel {
private final JPasswordField passwordField = new JPasswordField(12);
private boolean gainedFocusBefore;
/**
* "Hook" method that causes the JPasswordField to request focus the first time this method is called.
*/
void gainedFocus() {
if (!gainedFocusBefore) {
gainedFocusBefore = true;
passwordField.requestFocusInWindow();
}
}
public PasswordPanel() {
super(new FlowLayout());
add(new JLabel("Password: "));
add(passwordField);
}
public char[] getPassword() {
return passwordField.getPassword();
}
public static void main(String[] args) {
PasswordPanel pPnl = new PasswordPanel();
JOptionPane op = new JOptionPane(pPnl, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
JDialog dlg = op.createDialog("Who Goes There?");
// Wire up FocusListener to ensure JPasswordField is able to request focus when the dialog is first shown.
dlg.addWindowFocusListener(new WindowAdapter() {
@Override
public void windowGainedFocus(WindowEvent e) {
pPnl.gainedFocus();
}
});
if (op.getValue() != null && op.getValue().equals(JOptionPane.OK_OPTION)) {
String password = new String(pPnl.getPassword());
System.err.println("You entered: " + password);
}
}
}
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));
}