开发者

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

I'v开发者_C百科e 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?


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.


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();
    }
});


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();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜