2009-09-15 36 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