discodane
discodane

Reputation: 2095

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.

Upvotes: 0

Views: 3343

Answers (3)

Antoniossss
Antoniossss

Reputation: 32550

My guess is this will do the trick:

JOptionPane.showMessageDialog(null, "You have failed!","Login failed!", JOptionPane.ERROR_MESSAGE);

shows error dialog with message and title + OK button.

Upvotes: 0

Inzimam Tariq IT
Inzimam Tariq IT

Reputation: 6758

You can access JOptionPane button like this

int option = JOptionPane.showConfirmDialog(this, "Do you really want to close?");

And do your job :). Here is code

int option = JOptionPane.showConfirmDialog(this, "Wrong Username/Password");
if (option == JOptionPane.OK_OPTION){
        JOptionPane.showMessageDialog(this, "You Pressed Yes button!");
    }
else if (option == JOptionPane.CANCEL_OPTION){
        JOptionPane.showMessageDialog(this, "You Pressed Cancel button!");
    }

Upvotes: 0

Tricky12
Tricky12

Reputation: 6820

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]);

Upvotes: 1

Related Questions