在 JDialog
中使用 JOptionPane
来显示 JPasswordField
的概念之前已经被问过并回答过,但对于某些人来说这是我无法在 Java 7 (Oracle) 下的 Mac OS 上关注 JPasswordField
的原因。以下代码适用于 Windows,并使用 ComponentListener
将焦点设置到 componentShown
上的 JPasswordField
。我什至尝试将其包装在 invokeLater
中,尽管我认为这不是必需的,因为我在 EDT 上执行此操作。
private String passwordPrompt(String p) {
String thePassword = null;
final JPasswordField pf = new JPasswordField();
JOptionPane op = new JOptionPane(pf, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog d = op.createDialog(p);
d.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
pf.requestFocusInWindow();
}
});
}
@Override
public void componentHidden(ComponentEvent e) {}
@Override
public void componentResized(ComponentEvent e) {}
@Override
public void componentMoved(ComponentEvent e) {}
});
if (uIcon != null) {
d.setIconImage(new ImageIcon(uIcon).getImage());
}
d.setLocationRelativeTo(T);
d.setVisible(true);
if (op.getValue() == JOptionPane.OK_OPTION) {
thePassword = new String(pf.getPassword());
}
if ((thePassword == null) || thePassword.isEmpty()) {
thePassword = null;
}
d.dispose();
return thePassword;
}
该函数基本上会提示用户输入密码,但我希望在显示对话框时将焦点放在 JPasswordField
上。我是否做错了什么或者我遇到了 Mac 操作系统的怪癖之一?
最佳答案
使用 WindowFocusListener
,这似乎可以在 Windows 和 Mac OS (Mavericks 10.9.5/Java 8) 下工作
final JPasswordField pf = new JPasswordField(10);
JOptionPane op = new JOptionPane(pf, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog d = op.createDialog("Test");
d.addWindowFocusListener(new WindowAdapter() {
@Override
public void windowGainedFocus(WindowEvent e) {
pf.requestFocusInWindow();
}
});
d.pack();
d.setLocationRelativeTo(null);
d.setVisible(true);
关于java - MacOS 上 JOptionPane 中的 JPasswordField 焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29839559/