Set Cursor On A JTextField

29,109

Solution 1

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.

Solution 2

this works properly for cursor position textField.requestFocus();

Share:
29,109
Admin
Author by

Admin

Updated on July 16, 2022

Comments

  • Admin
    Admin almost 2 years

    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