4

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

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Zenith Blade
  • 43
  • 1
  • 1
  • 3
  • possible duplicate of http://stackoverflow.com/questions/6723257/how-to-set-focus-on-jtextfield – BevynQ Sep 20 '13 at 04:40
  • 2
    This is kind of difficult, because you actually have little or no idea of when the application will become available to the user. You could try using `SwingUtilities.invokeLater` and make a `requestFocusInWindow` call... – MadProgrammer Sep 20 '13 at 04:40

2 Answers2

11

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Wow, it worked! Indeed, I was using a JLabel first like "Insert something" and then the JTextField. Didn't know I must use the method after the window is visible, and none mentioned it too =/ Thanks man – Zenith Blade Sep 20 '13 at 04:52
  • A JLabel is not focusable so your text field should still get focus automatically. You must have some other problem with your code. – camickr Sep 20 '13 at 05:19
  • Well, I made an example by deleting the JLabel at all and still JTextField wasn't focused, meaning you had to click and then write on it. Don't know what's wrong but requestFocusInWindow() worked. – Zenith Blade Sep 20 '13 at 06:00
  • My apologies for not fully trying the above before sending a comment. To clarify for anyone who reads this, using both of the examples in the answer will result in both the button being the default and the cursor starting inside the JTextBox. – jesric1029 Oct 13 '15 at 20:53
1

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