Search code examples
actionlistenerjoptionpane

Adding action to JOptionPane buttons


I have an error dialog box show up when a user puts in bad login information (bad password/username).

I created the error box using a JOptionPane, but the "Ok" button doesn't do anything.

I can't figure out how to access the button to call dispose() or something on that particular dialog box.

Here is what i have:

final JDialog error = new JDialog();
error.setTitle("Login Failed");
final JOptionPane optionPane = new JOptionPane(
        "Invalid Username/Password",
        JOptionPane.INFORMATION_MESSAGE);
error.add(optionPane);

optionPane.actionPerformed(new ActionPerformed() {

    public void actionPerformed(ActionEvent e)
    {
        error.dispose();
    }
});
error.setLocation(100,100);
error.setSize(new Dimension(300,150));
error.setModal(true);
error.setVisible(true);

Please help.


Solution

  • You can just use one of the showXxxDialog() in the API.

    http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html

    Object[] options = { "OK", "CANCEL" };
    JOptionPane.showOptionDialog(null, "Click OK to continue", "Warning",
        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
        null, options, options[0]);
    

    So for you, it would be something like this:

    Object[] options = { "OK", "CANCEL" };
    JOptionPane optionPane = new JOptionPane();
    optionPane.showOptionDialog(null, "Invalid Username/Password", "Warning",
        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
        null, options, options[0]);