Zenith Blade
Zenith Blade

Reputation: 43

Set Cursor On A JTextField

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

Upvotes: 4

Views: 33481

Answers (2)

camickr
camickr

Reputation: 324207

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.

Upvotes: 11

Shivam Sharma
Shivam Sharma

Reputation: 11

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

Upvotes: 1

Related Questions