JOptionPane with username and password

I have my own dialog that appears with two text fields, two JLabel and "ok" JButton. A popup window is a login window. The window works fine, I just want to know how I can add a "cancel" JButton, so the user can cancel the input.

Here is my window code:

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 click on the "x" in the right corner, it will also close. But I want to cancel JButton if this is easily possible.

  • Thank you for your help.
+7
java jpanel jbutton joptionpane jtextfield
source share
3 answers

You need to use the OK , CANCEL confirmation dialog box.

 JOptionPane.showConfirmDialog( frame, panel, "login", JOptionPane.OK_CANCEL_OPTION); 
+6
source share

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

 jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ frameName.dispose(); } }); 
0
source share

You need to use JOptionPage.showOptionDialog () , which allows you to add buttons

0
source share

All Articles