Search code examples
javaswingfocusjtextfield

Unfocus on all JTextFields


How do i change the focus to be on a different field, such as a JButton? Or remove focusing on anything all together? Currently when my application loads, it is picking (what appears to be) a random JTextField to set focus to!

I've tried

text.setFocusable(true);
text.requestFocusInWindow();
text.requestFocus(true);
text.requestFocus();

but no luck here. I've also tried How to UnFocus a JTextField but i haven't had any luck with this working either.

The reason why I would like to not focus on the JTextFields is to avoid the hints from not appearing when the application first loads.

As you can see from the image, there is no hint on one of the JTextFields...

Any ideas? Thanks in advance..


Solution

  • The reason why I would like to not focus on the JTextFields is to avoid the hints from not appearing when the application first loads

    Text Prompt can support this requirement (ie. the prompt will disappear only when text is entered). Then you don't have to worry if the text field has focus or not.

    How do i change the focus to be on a different field, such as a JButton?

    You would use requestFocusInWindow() on the component AFTER the GUI is visible. But this doesn't make sense since the user would need to tab backwards to get to the text field. Or you could use the RequestFocusListener found in Dialog Focus. Again remember advanced users don't use the mouse.