JOptionPane with username and password input

Gerret picture Gerret · Aug 23, 2013 · Viewed 22.6k times · Source

I have my own Dialog pop up with two textfields, two JLabel and a "ok" JButton. The pop up is a login window. The window works perfect I just want to know how I am able to add a "cancel" JButton, so the user is able to cancel the login.

Here is my code for the window:

public Hashtable<String, String> login(JFrame frame) {
    Hashtable<String, String> logininformation = new Hashtable<String, String>();

    JPanel panel = new JPanel(new BorderLayout(5, 5));

    JPanel label = new JPanel(new GridLayout(0, 1, 2, 2));
    label.add(new JLabel("E-Mail", SwingConstants.RIGHT));
    label.add(new JLabel("Password", SwingConstants.RIGHT));
    panel.add(label, BorderLayout.WEST);

    JPanel controls = new JPanel(new GridLayout(0, 1, 2, 2));
    JTextField username = new JTextField();
    controls.add(username);
    JPasswordField password = new JPasswordField();
    controls.add(password);
    panel.add(controls, BorderLayout.CENTER);

    JOptionPane.showMessageDialog(frame, panel, "login", JOptionPane.QUESTION_MESSAGE);

    logininformation.put("user", username.getText());
    logininformation.put("pass", new String(password.getPassword()));
    return logininformation;
}

If you need it, here is a screenshot of the login window:

Login pop up

If you would click on the "x" at the right corner, it closes too. But I want a cancel JButton, if it is easily possible.

  • Thank you for help

Answer

Ravi K Thapliyal picture Ravi K Thapliyal · Aug 23, 2013

You need to use an OK, CANCEL type confirm dialog.

JOptionPane.showConfirmDialog(
            frame, panel, "login", JOptionPane.OK_CANCEL_OPTION);