How to make JOptionPane to handle Yes, No and Closed buttons in Java?

Java 8Object Oriented ProgrammingProgramming

For this, create JOptionPane.QUESTION_MESSAGE and with the user action display individual messages, for example −

int res = JOptionPane.showOptionDialog(new JFrame(), "Do you like Cricket?", "Hobbies",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
new Object[] { "Yes", "No" }, JOptionPane.YES_OPTION);
if (res == JOptionPane.YES_OPTION) {
   System.out.println("Selected Yes!");
}

Above, we have displayed a message on console if the user will selects YES button. The following is an example to make JOptionPane to handle Yes, No and Closed buttons −

Example

package my;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SwingDemo {
   public static void main(String args[]) {
      int res = JOptionPane.showOptionDialog(new JFrame(), "Do you like Cricket?","Hobbies",
         JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
         new Object[] { "Yes", "No" }, JOptionPane.YES_OPTION);
      if (res == JOptionPane.YES_OPTION) {
         System.out.println("Selected Yes!");
      } else if (res == JOptionPane.NO_OPTION) {
         System.out.println("Selected No!");
      } else if (res == JOptionPane.CLOSED_OPTION) {
         System.out.println("Window closed without selecting!");
      }
   }
}

Output

Let’s say you selected “Yes” above. The following will be visible in the Console in that case −

Let’s say you selected “No” above. The following will be visible in the Console in that case −

Let’s say you pressed “Cancel” (close) above. The following will be visible in the Console in that case −

raja
Published on 04-Jun-2019 08:29:17
Advertisements