DeanMWake
DeanMWake

Reputation: 923

JOptionPane.ShowConfirmDialog multiple inputs, focus text field

I have the following code to create a java confirm 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 shows by default the Okay button is selected. I have tried almost all possible ways to get the userName textField to focus but so far I have not managed. How would I do this?

For added information I have tried the following:

userName.requestFocus(true);
userName.grabFocus();
userName.requestFocusInWindow();
userName.requestFocus();

I even went so far as to test with a thread in case it was locking.

EventQueue.invokeLater(() -> {
    userName.grabFocus();
    userName.requestFocus();
});

Upvotes: 3

Views: 2235

Answers (1)

DeanMWake
DeanMWake

Reputation: 923

Thanks, @Murat K.

It seems I had not 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() );

I then added the RequestFocusListener class from the following link:

http://www.camick.com/java/source/RequestFocusListener.java

To further understand JDialogs and how their focus works I would recommend reading the link provided by @Murat K. or by clicking here.

Upvotes: 2

Related Questions