Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a listener on the ok button of JOptionPane? [duplicate]

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);
like image 230
earthmover Avatar asked Sep 10 '13 09:09

earthmover


Video Answer


2 Answers

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.

like image 192
cyon Avatar answered Oct 06 '22 10:10

cyon


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.

like image 43
Vimal Bera Avatar answered Oct 06 '22 11:10

Vimal Bera