I have the following code:
JTextField uname = new JTextField(defaultUser);
JPasswordField passwd = new JPasswordField();
JTextField serverAddress = new JTextField(defaultServer);
JTextField port = new JTextField(Integer.toString(defaultPort));
final JComponent[] inputs = new JComponent[]{new JLabel("Username"), uname, new JLabel("Password"), passwd, new JLabel("Server Address"), serverAddress, new JLabel("Server Port"), port};
int var = JOptionPane.showConfirmDialog(parent, inputs, "Enter Connection Details", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (var != 0) {
return;
}
....
This creates a dialog box that prompts for some details to connect to a server. What I’d like is to make the password field the default selected. That is, the cursor is there by default so you can start typing it as soon as the pane appears, as opposed to having to select the password box first – By default, the OK button has focus.
I’ve tried with passwd.requestFocusInWindow() but it doesn’t work (because I think that the box has to be visible before calling that for it to work). I also tried overriding passwd’s requestFocus method with various content, but it didn’t fly either (probably because it’s not getting called anyway….)
Note: I know that some of the other JOptionPane methods have default value parameters, but they have issues laying out the input boxes, so they’re no good to me.
Anyone got any ideas? It’s not a deal breaker, so I won’t be too upset if it can’t be done easily.
Cheers
Try adding a ComponentListener to the password field, and when it becomes visible then invoke #requestFocusInWindow
Update:
JOptionPanemakes the [OK] button default in the dialog and focuses it when the dialog is shown. So the solution is not that obvious… we have to add aHierarchyListenerand wait until the password field is added to dialog, then check if the dialog’sJRootPanehave a default button and if so add aFocusListener, finally when the button gets permanent focus switch focus to the password field:This solution works but it’s a bit hacky… An alternative is to create a custom “DatabaseConnectionDialog”, something like @syb0rg’s answer.