Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 201
Kenjiro Avatar asked Jul 17 '11 10:07

Kenjiro


People also ask

How do you set focus on TextField?

To give focus to a text field as soon as it's visible, use the autofocus property. TextField( autofocus: true, );

How do I center text in JTextField?

Just use the setBounds attribute. Jtextfield. setBounds(x,x,x,x);


1 Answers

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.

like image 190
Lukas Knuth Avatar answered Sep 17 '22 14:09

Lukas Knuth