JOptionPane获取密码

JOptionPane可以用来从用户获取stringinput,但在我的情况下,我想在showInputDialog显示一个密码字段。

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

是的,可以使用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)); } 

最简单的事情是使用JOptionPaneshowConfirmDialog方法,并传入一个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); } 

编辑

以下是使用自定义JPanelJPasswordField一起显示消息的示例。 根据最近的评论,我也(匆忙)添加了代码,以允许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); } } } 

你可以创build你自己的扩展JDialog的对话框,然后你可以放任何你想要的东西。

如果你这样做,这个对话看起来好多了

 dlg.setVisible(true); 

没有这一点,你根本看不到它。

 pPnl.gainedFocus(); 

应该

 pPnl.gainedFocus(); 

除此之外,它很好。 感谢代码。 为Swing节省了时间。

另外,如果您不想每次打开对话框都要在后台运行,则需要使用类似于

 dlg.dispatchEvent(new WindowEvent(dlg, WindowEvent.WINDOW_CLOSING)); dlg.dispose(); // else java VM will wait for dialog to be disposed of (forever)