Can't get keyboard focus on JTextField in JDialog
I have a Swing app that has a JDialog
pop up and ask for a username and password. I thought it'd be good to have the keyboard focus already in the username field, but everything I've tried so far doesn't work (even though one solution I tried works for a different text field in the program), so....I need some help. Here's my code:
//JTextField usernameField = ...
JDialog dialog = pane.createDialog("Password:");
dialog.setVisible(true);
//Take 1
usernameField.requestFocusInWindow();
//Take 2
dialog.addWindowFocusListener(new WindowAdapter() {
public void windowGainedFocus(WindowEvent e) {
usernameField.requestFocusInWindow();
}
});
//Take 3 - This is what I used elsewhere quite successfully
dialog.addComponentListener(new ComponentAdapter() {
public void componentShown(ComponentEvent e ) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
usernameField.requestFocusInWindow();
}
});
}
});
For what it's worth, this is with Linux / X11 / Openbox. And when I 开发者_运维技巧use GTK, I have to press Tab
once to select the appropriate field, but when I use Metal, I have to press it twice.
Thanks in advance.
See Dialog Focus for tips & strategies.
精彩评论