How to Set Focus on JTextField?

Kenjiro picture Kenjiro · Jul 17, 2011 · Viewed 137.1k times · Source

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?

Answer

Lukas Knuth picture Lukas Knuth · Jul 17, 2011

If you want your JTextField to be focused when your GUI shows up, you can use this:

in = new JTextField(40);
f.addWindowListener( new WindowAdapter() {
    public void windowOpened( WindowEvent e ){
        in.requestFocus();
    }
}); 

Where f would be your JFrame and in is your JTextField.