om.
om.

Reputation: 4239

How do you set a focus on JTextField in Swing?

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

Upvotes: 50

Views: 93360

Answers (5)

phunehehe
phunehehe

Reputation: 8778

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

Upvotes: 96

Jeff_Alieffson
Jeff_Alieffson

Reputation: 2882

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

Upvotes: 5

Marc
Marc

Reputation: 1912

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) {
    }
}

Upvotes: 6

Rhea
Rhea

Reputation: 311

This would work..

SwingUtilities.invokeLater( new Runnable() { 

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

Upvotes: 31

camickr
camickr

Reputation: 324197

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. "

Upvotes: 16

Related Questions