使用JOptionPane在JDialog中显示JPasswordField的概念已经被问到并得到了回答,但由于某些原因,我无法在Java7 (Oracle)下关注Mac上的JPasswordField。下面的代码在Windows上工作,并使用ComponentListener将焦点设置为JPasswordField on componentShown。我甚至尝试过用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的怪癖之一?
发布于 2015-04-24 06:08:50
使用WindowFocusListener,这似乎适用于Windows和Mac (小牛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);发布于 2015-04-24 05:48:17
看看对话焦点。它使用可能对您有用的HierarchyListener。
https://stackoverflow.com/questions/29839559
复制相似问题