JOptionPane获取密码

Aha*_*med 47 java passwords user-interface swing joptionpane

JOptionPane可用于从用户获取字符串输入,但在我的情况下,我想在中显示密码字段showInputDialog.

我需要的方式是应该屏蔽用户给出的输入并且返回值必须在char[].我需要一个带有消息,密码字段和两个按钮的对话框.可以这样做吗?谢谢.

Eng*_*uad 63

是的,可以使用JOptionPane.showOptionDialog().像这样的东西:

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));
}
Run Code Online (Sandbox Code Playgroud)

  • JPasswordField(10)不接受超过10的密码.更好地使这个更宽或使用像@Adamski下面的无参数构造函数.OK也应该是默认选项,因为许多用户在输入密码后会不习惯按Enter键.如果取消是默认值,则输入密码后输入将只取消对话框. (4认同)
  • 当对话框出现时,如何为密码字段指定焦点? (3认同)

Ada*_*ski 39

最简单JOptionPaneshowConfirmDialog方法是使用方法并传入对a的引用JPasswordField; 例如

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);
}
Run Code Online (Sandbox Code Playgroud)

编辑

下面是一个使用自定义JPanel显示消息的示例JPasswordField.根据最新的评论,我也(草率地)添加了代码,以便在JPasswordField首次显示对话框时获得焦点.

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);
      }
  }
}
Run Code Online (Sandbox Code Playgroud)