Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 699
Zenith Blade Avatar asked Dec 20 '22 00:12

Zenith Blade


2 Answers

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.

like image 141
camickr Avatar answered Jan 02 '23 15:01

camickr


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

like image 33
Shivam Sharma Avatar answered Jan 02 '23 16:01

Shivam Sharma