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
-
Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses – MadProgrammer Jun 18 '15 at 06:04
-
There's no real way to know when a component is actually displayed on the screen. You might use `SwingUtilities.invokeLater` or provide some kind of method that allows callers to tell you when they've added your component to a window (and made it visible) – MadProgrammer Jun 18 '15 at 06:07
1 Answers
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)

- 7,972
- 21
- 79
- 122