2009-09-15 37 views
32

我已經在Java中使用Swing創建了一個表單。在表單中,我使用了一個文本框,在每次按下按鍵時都必須設置焦點。如何將焦點設置在Java中的特定組件上?如何在Swing中設置Textfield的焦點?

+1

10個問題,沒有人回答接受... – 2009-09-15 06:10:26

回答

73

Component.requestFocus()給你你需要什麼?

+0

謝謝,讓我看看它是否適用於我 – 2009-09-15 06:10:36

+8

花了我五分鐘找到它...非常適合「簡單」搜索:-(啊,Java API文檔不是典範清楚無論如何:-) – Joey 2009-09-15 06:12:48

+3

僅供參考,[jComponent的javadocs](http://docs.oracle.com/javase/7/docs/api/index.html)說'requestFocus()',「使用這個方法是不鼓勵的,因爲它的行爲是依賴於平臺的我們推薦使用[requestFocusInWindow()](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#requestFocusInWindow())。如果您想了解關於焦點的更多信息,請參見The Java Tutorial中的一節,請參閱[如何使用焦點子系統](http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html)。 「 – 2014-09-11 14:26:56

13

既然我們已經搜索了API,那麼我們需要做的就是讀取API。

根據API文檔:

「正因爲如此 方法的焦點行爲是與平臺相關的, 開發商大力鼓勵 使用requestFocusInWindow時 可能。」

21

這會工作..

SwingUtilities.invokeLater(new Runnable() { 

public void run() { 
     Component.requestFocus(); 
    } 
}); 
3

請注意,上述所有因爲某種原因在JOptionPane中失敗。多試錯(比上述既定的5分鐘,反正)後,這裏是最後的工作:

 final JTextField usernameField = new JTextField(); 
// ... 
     usernameField.addAncestorListener(new RequestFocusListener()); 
     JOptionPane.showOptionDialog(this, panel, "Credentials", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null); 


public class RequestFocusListener implements AncestorListener { 
    @Override 
    public void ancestorAdded(final AncestorEvent e) { 
     final AncestorListener al = this; 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       final JComponent component = e.getComponent(); 
       component.requestFocusInWindow(); 
       component.removeAncestorListener(al); 
      } 
     }); 
    } 

    @Override 
    public void ancestorMoved(final AncestorEvent e) { 
    } 

    @Override 
    public void ancestorRemoved(final AncestorEvent e) { 
    } 
} 
+1

謝謝你的解決方案,這是唯一的方法它工作。 – MyPasswordIsLasercats 2015-01-12 11:23:55

3

您還可以使用JComponent.grabFocus();是同

+0

[JComponent.grabFocus()](http://docs.oracle.com/javase/8/docs/api/javax/swing/JComponent.html#grabFocus--)的Javadoc明確指出此方法應該不被客戶端代碼使用,並建議使用'requestFocusInWindow()'方法,這在其他答案中已經提到。 – 2015-05-23 08:50:06