Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 −

Advertisements