Setting default cursor on a text field in a panel in java swing

1.2k views Asked by At

I am making a application in Java that uses a JTextField. Now, I want, as soon as I run the app, the cursor to be put automatically in that so that the user doesn't have to click on it and then write the text. I have tried requestFocusInWindow() but it doesn't work.The focus goes to the Panel present in the Jframe first but I have to click on the text field to edit it. Can anyone help me solve this,really appreciate it. Thanks a lot

1

There are 1 answers

0
Entity On

Check what requestFocusInWindow() is returning. It returns true if it is likely to succeed, and false if it definitely fails.

Also, try waiting until JTextField's parents are visible when you call requestFocusInWindow(). In my experience, calling the method before parents are visible usually doesn't work.

Here's a paragraph from the documentation:

If you want to ensure that a particular component gains the focus the first time a window is activated, you can call the requestFocusInWindow method on the component after the component has been realized, but before the frame is displayed.

And then provides this code sample:

frame.pack(); // Realize the components.
button.requestFocusInWindow(); 
frame.setVisible(true); // Display the window.

I suspect that when the components are "realized" (whatever that means), Java automatically delegates the focus. I also suspect that if you do not call pack(), the components are not "realized" until you call setVisible(true)