How to add listener to ok button in JOptionPane?

How to add a listener when you click OK in JOptionPane.INFORMATION_MESSAGE .

My JOptionPane:

 JOptionPane.showMessageDialog(null, "Your password is: " + password, "Your Password", JOptionPane.INFORMATION_MESSAGE); 
+6
source share
2 answers

The showMessageDialog method returns void when the user closes or clicks ok. But you can use the JOptionPane.showOptionDialog method with a single DEFAULT_OPTION for the OK button. showOptionDialog will return 0 if it clicked OK 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 javadoc says:

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

+7
source

When the JOptionPane button is pressed, it returns the index value of the button. By checking the value, you can find out if the Ok button is pressed or not.

+3
source

Source: https://habr.com/ru/post/953551/


All Articles