10

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
Gerret
  • 2,948
  • 4
  • 18
  • 28

3 Answers3

9

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

JOptionPane.showConfirmDialog(
            frame, panel, "login", JOptionPane.OK_CANCEL_OPTION);
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
0

You can use dispose() function on JFrame to close the frame when you click on the button. Like this

jButton1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e){
        frameName.dispose();
    }
});
Danielson
  • 2,605
  • 2
  • 28
  • 51
Vimal Bera
  • 10,346
  • 4
  • 25
  • 47
  • Yes that a good beginning but I have more the problem that I cant add a secound button and/or dont know where! – Gerret Aug 23 '13 at 05:54
0

You need to use JOptionPage.showOptionDialog() which enables to add buttons

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
  • okay is understandable but I have the problem that I dont know what I have to fill in messageType, icon, options and initialValue... could you help me with that too? – Gerret Aug 23 '13 at 06:01
  • messageType can be any one of `ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE` , for the rest, you can pass `null`. You can consult docs for further information – Prasad Kharkar Aug 23 '13 at 06:05
  • ...Well I dont get it ok pass with null no problem but I have a OptionType and a MessageType what is the difference? And at my code I used `QUESTION_MESSAGE` at OptionType. So what at to OptionType... – Gerret Aug 23 '13 at 06:08