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

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



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 −

Updated on: 2019-07-30T22:30:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements