简体   繁体   English

你如何在Swing中设置Textfield的焦点?

[英]How do you set a focus on Textfield in Swing?

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

Component.requestFocus()为您提供所需的内容吗?

This would work.. 这会工作..

SwingUtilities.invokeLater( new Runnable() { 

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

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。”

Note that all of the above fails for some reason in a JOptionPane. 请注意,以上所有内容都因JOptionPane中的某些原因而失败。 After much trial and error (more than the above stated 5 minutes, anyway), here is what finally worked: 经过多次试验和错误(无论如何,超过上述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) {
    }
}

You can use also JComponent.grabFocus(); 你也可以使用JComponent.grabFocus(); it is the same 这是相同的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM