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 you want specify the component with focus before the window is visible then you can use the RequestFocusListener approach from Dialog Focus.