问题
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
回答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 you want specify the component with focus before the window is visible then you can use the RequestFocusListener
approach from Dialog Focus.
回答2:
this works properly for cursor position textField.requestFocus();
来源:https://stackoverflow.com/questions/18908902/set-cursor-on-a-jtextfield