Pops
Pops

Reputation: 30828

How can I make a Swing text area have the focus as soon as it is loaded?

I've created a simple Swing panel that, when loaded, takes up my application's entire window. It contains two JTextAreas and a handful of buttons. I want one of the text areas to have the focus when the panel loads, so that the user can immediately start typing instead of having to click on the text area first. How can I achieve this?

Upvotes: 1

Views: 7013

Answers (3)

Sukhbir
Sukhbir

Reputation: 661

You just need to call requestFocus method of Jcomponent class,

public void requestFocus()

On the Component that you want to focus. And pleas make sure that you call this method after setVisible is called for its parent component.

For example:- You have a Jframe in which you added a JTextArea, so after calling you should call in following order:-

jframe.setVisible(true); jarea.requestFocus();

Upvotes: 0

camickr
camickr

Reputation: 324118

By default focus goes to the first component defined on the window.

If this is not the component you want to have focus then you need to request focus once the window is realized.

The Dialog Focus example shows a couple of ways to do this.

Upvotes: 4

theomega
theomega

Reputation: 32041

See here the Documentation which contains exactlly what you are searching for (I think):

A component can also be given the focus programmatically, such as when its containing frame or dialog-box is made visible. This code snippet shows how to give a particular component the focus every time the window gains the focus:

//Make textField get the focus whenever frame is activated.
frame.addWindowFocusListener(new WindowAdapter() {
    public void windowGainedFocus(WindowEvent e) {
        textField.requestFocusInWindow();
    }
});

Upvotes: 4

Related Questions