2014-02-12 67 views
0

我使用JOptionPane創建了一個密碼字段。當我運行程序時,JOptionPane出現並且看起來很棒,但是焦點始終轉到確定按鈕。我想要在密碼字段開始焦點。我試過requestFocus()requestFocusInWindow(),但這似乎不起作用。有什麼特別的,我需要去關注密碼領域?在JOptionPane中設置焦點JPasswordField

見下面我的代碼:

JPasswordField pf = new JPasswordField(); 
pf.requestFocusInWindow(); 
int okCxl = JOptionPane.showConfirmDialog(null, pf, "ENTER SUPERUSER PASSWORD", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); 
+0

的可能重複[如何創建時將焦點設置裏面的JOptionPane具體的JTextField?](http://stackoverflow.com/questions/6478394/how-to-set-focus-on-specific-jtextfield-內部-的JOptionPane-時創建的) – Laf

回答

1

你必須創建JOPtionPane的實例,並使用setWantsInput(boolean)方法。這並不方便,但您使用的構建器方法實際上僅適用於基本情況。然後,您需要在對話框中添加ComponentListener以請求選擇密碼字段。您可以在JOptionPane javadoc上找到更多類似的文檔。

final JPasswordField pf = new JPasswordField(); 
    //Create OptionPane & Dialog 
    JOptionPane pane = new JOptionPane(pf, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); 
    JDialog dialog = pane.createDialog("ENTER SUPERUSER PASSWORD"); 
    //Add a listener to the dialog to request focus of Password Field 
    dialog.addComponentListener(new ComponentListener(){ 

     @Override 
     public void componentShown(ComponentEvent e) { 
      pf.requestFocusInWindow(); 
     } 
     @Override public void componentHidden(ComponentEvent e) {} 
     @Override public void componentResized(ComponentEvent e) {} 
     @Override public void componentMoved(ComponentEvent e) {} 
     }); 

    dialog.setVisible(true);