Search code examples
javaswinguser-interfacejpasswordfield

Textfield doesn't maintain focus (AncestorListener)


I am using Camick's code to request focus on my JPasswordField (at the end):

The focus is on the password field the first time the showConfirmDialog appears, but when the dialog appears the second time (either due to wrong password, or clicking the button again), the focus is moved to 'OK', and then back to the password field the next time. Here is my code...

int resp;
String orgPwd;
String givenPwd;
JPasswordField pwd = new JPasswordField(10);

do {
    pwd.setText("");
    pwd.addAncestorListener(new RequestFocusListener());
    diagResp = JOptionPane.showConfirmDialog(null, pwd, "Enter Password", JOptionPane.OK_CANCEL_OPTION);
    givenPwd = new String(pwd.getPassword());

    if (resp != JOptionPane.OK_OPTION) { return false; }
} while (!givenPwd.equals(orgPwd));

Solution

  • Move pwd.addAncestorListener(new RequestFocusListener()); before the do {, you only want to add it once, not every time the loop cycles...

    Also, you'll want to read and understand what the code is doing before using it.

    By default the RequestFocusListener is automatically removed when the ancestorAdded event occurs, try using...

    pwd.addAncestorListener(new RequestFocusListener(false));
    

    ...instead