如何请求关注JOptionPane中的JPasswordField?

时间:2016-11-18 16:31:48

标签: java swing joptionpane

I've learned in this other question that it's possible by overriding the addNotify method,但那不起作用。这是我的代码:

ResultSetImpl.getNativeTimestampViaParseConversion(int, Calendar, TimeZone, boolean)

一旦出现JOptionPane,默认焦点就在" Ok"按钮:

enter image description here

如果我在显示对话框之前只是private boolean accessPasswordFrame(String titleText, String labelText, String errorMessage, int accessType) { JPasswordField passwordField = new JPasswordField() { public void addNotify() { super.addNotify(); requestFocus(); } }; final JComponent[] inputs = new JComponent[] { new JLabel(labelText), passwordField }; int result = JOptionPane.showConfirmDialog(frame, inputs, titleText, JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { String rootPass = new String(passwordField.getPassword()); if (accessType == ADMIN_TYPE) { if (rootPass.equals(ROOT_PASSWORD)) { return true; } else { JOptionPane.showMessageDialog(null, errorMessage, "Erro", JOptionPane.ERROR_MESSAGE); } } else if (accessType == USER_TYPE) { if (PasswordFrame.getPasswords() != null) { for (Map.Entry<String, String> e : PasswordFrame.getPasswords().entrySet()) { if (rootPass.equals(e.getValue())) { lastUser = e.getKey(); return true; } else { JOptionPane.showMessageDialog(null, errorMessage, "Erro", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(null, "Usuários cadastrados não existem.", "Erro", JOptionPane.ERROR_MESSAGE); } } } return false; } ,那么它也无法正常工作。

1 个答案:

答案 0 :(得分:4)

您可以向组件添加侦听器,以便在选项窗格可见时调用侦听器,然后您可以请求关注组件。

查看Dialog Focus中找到的RequestFocusListener课程,了解可重复使用的解决方案。