简体   繁体   中英

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.

According to the API documentation:

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

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:

        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(); it is the same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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