Question

I am trying to request focus on the first username field, however it's not focusing in on the text field. Here's my code:

JTextField username = new JTextField();
JTextField password = new JPasswordField();
JTextField prefix = new JTextField();
username.requestFocus();
Object[] message = {
    "Username:", username,
    "Password:", password,
    "Prefix:", prefix
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
username.requestFocus();
if (option == JOptionPane.OK_OPTION) {
    return ls.login(username.getText(), password.getText(), prefix.getText());
} else {
    return false;
}

What can I do to request the focus of the username text field?

Was it helpful?

Solution

Here is how to do:

final JTextField username = new JTextField();
JTextField password = new JPasswordField();
JTextField prefix = new JTextField();
JPanel gridLayout = new JPanel(new GridLayout(6, 1));
gridLayout.add(new JLabel("Username:"));
gridLayout.add(username);
gridLayout.add(new JLabel("Password:"));
gridLayout.add(password);
gridLayout.add(new JLabel("Prefix:"));
gridLayout.add(prefix);

username.addAncestorListener(new AncestorListener() {
    @Override
    public void ancestorRemoved(AncestorEvent pEvent) {
    }

    @Override
    public void ancestorMoved(AncestorEvent pEvent) {
    }

    @Override
    public void ancestorAdded(AncestorEvent pEvent) {
        // TextField is added to its parent => request focus in Event Dispatch Thread
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                username.requestFocusInWindow();
            }
        });
    }
});

int option = JOptionPane.showConfirmDialog(null, gridLayout, "Login",
    JOptionPane.OK_CANCEL_OPTION);

I simply replaced your Object[] message with a JPanel object, and used a AncestorListener to get notified when the text field is added to its parent.

Note: I don't know why it doesn't work with your Object[] message.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top