繁体   English   中英

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

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

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

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

这会工作..

SwingUtilities.invokeLater( new Runnable() { 

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

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

根据API文档:

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

请注意,以上所有内容都因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) {
    }
}

你也可以使用JComponent.grabFocus(); 这是相同的

暂无
暂无

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

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