I make my game run without mouse so using pointer is not a choice. High Score menu will show when player lose.
this is my code
highScore=new MyTextField("Your Name");
highScore.addKeyListener(this);
highScore.setFont(font);
highScore.requestFocusInWindow();
I have tried
highScore.setFocusable(true);
highScore.requestFocusInWindow();
highScore.requestFocus(true);
highScore.requestFocus();
but still not gained focus on my JTextField
.
How to focus it?
While
yourTextField.requestFocus()
is A solution, it is not the best since in the official Java documentation this is discourage as the methodrequestFocus()
is platform dependent.The documentation says:
Use
yourJTextField.requestFocusInWindow()
instead.If you want your
JTextField
to be focused when your GUI shows up, you can use this:Where
f
would be yourJFrame
andin
is yourJTextField
.If the page contains multiple item and like to set the tab sequence and focus I will suggest to use FocusTraversalPolicy.
grabFocus() will not work if you are using FocusTraversalPolicy.
Sample code
In my case nothing above worked untill I called requestFocus() AFTER my constructor has returned.
MyPanel.initFocus() would have:
And it works.
It was not working for me when tried to use:
But - I found a solution ! Very primitive, but works.
Just jump to the field by java.awt.Robot using key "Tab". For example:
If you should press multiple times on "Tab" to get your Component you can use below method:
Definition:
If your Component location is dynamic, you can run over the while loop without limitation, but add some focus listener on the component, to stop the loop once arrived to it.