2014-03-27 86 views
2

我正在嘗試請求專注於第一個用戶名字段,但它並不專注於文本字段。這裏是我的代碼:Java username.requestFocus();不工作在JOptionPane

JTextField username = new JTextField(); 
JTextField password = new JPasswordField(); 
JTextField prefix = new JTextField(); 
username.requestFocus(); 
Object[] message = { 
    "Username:", username, 
    "Password:", password, 
    "Prefix:", prefix 
}; 

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION); 
username.requestFocus(); 
if (option == JOptionPane.OK_OPTION) { 
    return ls.login(username.getText(), password.getText(), prefix.getText()); 
} else { 
    return false; 
} 

我能做些什麼來請求用戶名文本字段的重點?

回答

3

這裏是如何做到:

final JTextField username = new JTextField(); 
JTextField password = new JPasswordField(); 
JTextField prefix = new JTextField(); 
JPanel gridLayout = new JPanel(new GridLayout(6, 1)); 
gridLayout.add(new JLabel("Username:")); 
gridLayout.add(username); 
gridLayout.add(new JLabel("Password:")); 
gridLayout.add(password); 
gridLayout.add(new JLabel("Prefix:")); 
gridLayout.add(prefix); 

username.addAncestorListener(new AncestorListener() { 
    @Override 
    public void ancestorRemoved(AncestorEvent pEvent) { 
    } 

    @Override 
    public void ancestorMoved(AncestorEvent pEvent) { 
    } 

    @Override 
    public void ancestorAdded(AncestorEvent pEvent) { 
     // TextField is added to its parent => request focus in Event Dispatch Thread 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       username.requestFocusInWindow(); 
      } 
     }); 
    } 
}); 

int option = JOptionPane.showConfirmDialog(null, gridLayout, "Login", 
    JOptionPane.OK_CANCEL_OPTION); 

我只是一個JPanel對象換成你Object[] message,並使用AncestorListener當文本字段添加到其父母得到通知。

注意:我不知道爲什麼它不適用於您的Object[] message

+0

username.requestFocusInWindow();在invokeLater中 – mKorbel