Reputation: 3178
One school of thought says to add a window listener and set focus when the windowOpened event fires:
addWindowListener(new WindowAdapter(){
public void windowOpened( WindowEvent e){
txtMessage.requestFocus();
}
});
The other school of thought says to use the SwingUtilities.invokeLater method to set focus in a separate thread.
SwingUtilities.invokeLater(new Runnable()
{
public void run() {
field.requestFocus();
}
});
Can anyone tell me which is best practice or when you would choose one over the other? When using the threaded solution, is it possible for the thread to get lost and focus never set?
Upvotes: 1
Views: 1369
Reputation: 324207
The best practice is to use requestFocusInWindow()
not requestFocus().
I prefer the second approach. I think it will work in all cases.
Panels should be created independently of the Window (JFrame or JDialog) that they will be added to so the panel will not have a reference to the Window when it is constructed. For example:
JPanel panel = new CustomPanel();
JFrame frame = new JFrame();
frame.add( panel );
For a third approach you can check out the RequestFocusListener.
Upvotes: 2
Reputation: 2939
addWindowListener(new WindowAdapter(){
public void windowOpened( WindowEvent e){
SwingUtilities.invokeLater(new Runnable()
{
public void run() {
field.requestFocusInWindow();
}
});
}
});
Upvotes: 3
Reputation: 5435
All updates to the GUI must be done on the Event-Dispatch Thread (EDT). If you're unsure whether or not you're on it, invokeLater(...) will always guarantee it. It won't harm anything if you use it and don't need it.
Also, you should use field.requestFocusInWindow();
Upvotes: 4