JOptionPane.ShowConfirmDialog multiple inputs, focus textbox
I have the following code to create a java confirmation dialog:
JTextField userName = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
"Username:", userName,
"Password:", password
};
int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
When this dialog box shows by default, the button is selected Okay
. I have tried almost every possible way that the textField userName is focused, but so far I have failed. How should I do it?
For more information, I've tried the following:
userName.requestFocus(true);
userName.grabFocus();
userName.requestFocusInWindow();
userName.requestFocus();
I even went so far as to test the thread if it was blocking.
EventQueue.invokeLater(() -> {
userName.grabFocus();
userName.requestFocus();
});
source to share
Thanks, @Murat K.
I didn't seem to read the article carefully enough the first time.
To fix this, I added the following code to my class:
JTextField userName = new JTextField();
userName.addAncestorListener( new RequestFocusListener() );
Then I added the RequestFocusListener class from the following link:
http://www.camick.com/java/source/RequestFocusListener.java
For further understanding of JDialogs and how their focus works, I would recommend reading the link provided by @Murat K. or by clicking here .
source to share