Search code examples
javaswingjframejtextfieldcaret

Automatically set focus on JTextField


Cant find an answer for this (or most likely Im not asking properly).

How can I set focus on JTextField textfield1 as soon as my JFrame is initiated? by focus I mean the user can start typing right away without having to click on the JTextField.

I tried textfield1.setCaretPosition(0) and textfield1.moveCaretPosition(0), neither worked.

Also the focus stays on the submit button after clicking it (even if I call the above 2 after the click).


Solution

  • Focus is controlled in a number of ways in Swing, but in your case, the simplest might be to simply use JTextField#requestFocusInWindow

    It's a little off topic, but you might want to take a look at How to use the a Focus Subsystem