I am making a small 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 pretty much everything that I found on the net: setCaretPosition(0), grabFocus(), requestFocusInWindow() or requestFocus() but none of them worked! I am desperate, can you please help me solve this? Thanks a lot
By default focus will go to the first component on the Window.
If the text field is not the first component then you can use:
textField.requestFocusInWindow();
However, you must invoke this method AFTER the window is visible.
If the window is not visible then you should be able to use a Java lambda:
EventQueue.invokeLater( () -> textField.requestFocusInWindow() );
The above code will be placed on the end of the Event Dispatch Thread (EDT)
, so it should execute after the window has been made visible.
Or, you can use the RequestFocusListener
approach from Dialog Focus.
Note, now that Java lambda's exist, this will be overkill in most situations, but it still has a place to be used for setting focus on modal dialogs.
this works properly for cursor position textField.requestFocus();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With