6

How can I add a listener on the click of "OK" button of JOptionPane.INFORMATION_MESSAGE.

My JOptionPane is:

JOptionPane.showMessageDialog(null, "Your password is: " + password, "Your Password", JOptionPane.INFORMATION_MESSAGE);
mKorbel
  • 109,525
  • 20
  • 134
  • 319
earthmover
  • 4,395
  • 10
  • 43
  • 74

2 Answers2

10

The showMessageDialog method returns void when the user closes or clicks ok. But you can use the method JOptionPane.showOptionDialog with a single DEFAULT_OPTION for the OK button. The showOptionDialog will return 0 if OK was clicked and -1 if the user closed the dialog.

int res = JOptionPane.showOptionDialog(null, "Hello", "Test", JOptionPane.DEFAULT_OPTION,
        JOptionPane.INFORMATION_MESSAGE, null, null, null);

System.out.println(res);

You don't need a listener because the javadoc says:

Each showXxxDialog method blocks the caller until the user's interaction is complete.

cyon
  • 9,340
  • 4
  • 22
  • 26
3

When the button on JOptionPane is clicked, it returns the index value of button. By checking the value, you can get to know that Ok button is clicked or not.

Vimal Bera
  • 10,346
  • 4
  • 25
  • 47