Search code examples
javaswingjtextfieldsetfocus

How to Set Focus on JTextField?


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?


Solution

  • 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.