[java] Setting the focus to a text field

I have an application developed in netbeans and I want to set the focus to a certain jTextField when a panel is displayed. I have read a number of post and have tried various methods but non have worked. One of the main issues is where to place the required code, which I believe in my case is this.txtMessage.requestFocusInWindow();

There are some posts that indicate using a Window Listener, however as netbeans has generated the GUI, I cannot see how to implement the interfaces as I cannot edit the code that creates the jPANEL etc. The whole thing is very frustrating and I really do not believe that this should be that difficult.

Just as a test I added the requestFocusInWindow(); to a button on the panel and it did set the focus to the desired input.

This question is related to java swing netbeans focus

The answer is

I have had a similar scenario where I needed to set the focus on a text box within a panel when the panel was shown. The panel was loaded on application startup, so I couldn't set the focus in the constructor. As the panel wasn't being loaded or being given focus on show, this meant that I had no event to fire the focus request from.

To solve this, I added a global method to my main that called a method in the panel that invoked requestFocusInWindow() on the text area. I put the call to the global method in the button that showed the panel, after the call to show. This meant that the panel would be shown and then the text area assigned the focus after showing the panel. Hope that makes sense and helps!

Also, you can edit most of the auto-generated code by right clicking on the object in design view and selecting customize code, however I don't think that it allows you to edit panels.

Similar questions with java tag:

Similar questions with swing tag:

Similar questions with netbeans tag:

Similar questions with focus tag: