Java 你如何在 Swing 中设置对 Textfield 的关注?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1425392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:55:30  来源:igfitidea点击:

How do you set a focus on Textfield in Swing?

javaswingfocus

提问by om.

I have created one form using Swing in Java.In the form I have used one textfield on which I have to set the focus whenever I press the key.How to set focus on a particular component in Java ?

我在 Java 中使用 Swing 创建了一个表单。在表单中,我使用了一个文本字段,每当我按下键时,我都必须在该文本字段上设置焦点。如何在 Java 中将焦点设置在特定组件上?

采纳答案by phunehehe

Would Component.requestFocus()give you what you need?

请问Component.requestFocus()给你你需要什么?

回答by camickr

Now that we've searched the API all we need to do is read the API.

现在我们已经搜索了 API,我们需要做的就是阅读 API。

According to the API documentation:

根据 API 文档:

"Because the focus behavior of this method is platform-dependent, developers are strongly encouraged to use requestFocusInWindow when possible. "

“因为此方法的焦点行为是平台相关的,所以强烈建议开发人员尽可能使用 requestFocusInWindow。”

回答by Rhea

This would work..

这会工作..

SwingUtilities.invokeLater( new Runnable() { 

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

回答by Marc

Note that all of the above fails for some reason in a JOptionPane. After much trial and error (more than the above stated 5 minutes, anyway), here is what finally worked:

请注意,由于某种原因,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) {
    }
}

回答by Jeff_Alieffson

You can use also JComponent.grabFocus();it is the same

你也可以使用JComponent.grabFocus();它是一样的