- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
- Related Articles
- How to create JavaScript alert with 3 buttons (Yes, No and Cancel)?
- How can I create a dialog box in Java with Yes No and cancel buttons?
- How to Generate Random Yes or No in Excel?
- How to create a dialog with “yes” and “no” options in JavaScript?
- How to Allow Only Yes or No Entry in Excel?
- How to use JOptionPane with Array Elements in Java?
- Java Program to set JComboBox in JOptionPane
- How to Calculate the Percentage of Yes and No from a List in Excel?
- How to handle EOFException in java?
- How to handle StringIndexOutOfBoundsException in Java?
- How to handle MalformedURLException in java?
- MySQL IF() to display custom YES or NO messages
- How to handle Assertion Error in Java?
- Java Program to set an icon for JOptionPane
- How to handle proxy in Selenium in Java?

Advertisements