I've learned in this other question that it's possible by overriding the addNotify method,但這不起作用。這裏是我的代碼:如何請求關注JOptionPane中的JPasswordField?
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;
}
一旦JOptionPane的出現,默認的焦點是「確定」按鈕:
如果我只是requestFocus()
之前顯示的對話框,它不工作也是如此。
'但那不行。「 - 你是否嘗試了該鏈接中的其他建議? – camickr