2016-11-18 43 views
1

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的出現,默認的焦點是「確定」按鈕:

enter image description here

如果我只是requestFocus()之前顯示的對話框,它不工作也是如此。

+0

'但那不行。「 - 你是否嘗試了該鏈接中的其他建議? – camickr

回答

4

您可以向組件添加偵聽器,以便在選項窗格變得可見時調用偵聽器,然後您可以請求焦點對組件。

檢出RequestFocusListener類找到Dialog Focus爲可重複使用的解決方案。

+0

'.addAncestorListener(new RequestFocusListener());'像魅力一樣工作,非常感謝你! –