如何在Swing中将焦点设置在JTextField上?

49

我使用Java的Swing创建了一个表格。在表格中,我使用了JTextField,每当我按键时都必须将焦点设置在上面。如何在Swing中将焦点设置在特定的组件上?

5个回答

94

11
参考JComponent的javadocs中提到,requestFocus()方法的使用不被建议,因为其行为依赖于特定平台。相反,建议使用requestFocusInWindow()方法。如果您想了解更多关于焦点的信息,请参阅The Java Tutorial中的How to Use the Focus Subsystem一节。 - Adam Mackler

30

这将起作用。

SwingUtilities.invokeLater( new Runnable() { 

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

1
这个对我很有效,尤其是因为我在我的应用程序中从一个屏幕切换到另一个屏幕时请求焦点。与其他方法不同,这个方法适用于我。 - matteoh

15

既然我们已经搜索了API,现在我们只需要读取API即可。

根据API文档:

“由于该方法的焦点行为取决于平台,强烈建议开发者尽可能使用requestFocusInWindow。”


5
请注意,所有以上方法在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) {
    }
}

5
你也可以使用JComponent.grabFocus();,它与前者相同。

3
JComponent.grabFocus() 的 Javadoc 明确指出此方法不应该被客户端代码使用,并建议使用 requestFocusInWindow() 方法,该方法已在其他答案中提到。 - Oleg Estekhin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接