如何在 Java 中让 JOptionPane 处理“是”、“否”和“关闭”按钮?
为此,创建 JOptionPane.QUESTION_MESSAGE 并在用户操作时显示某一个消息,例如 –
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!");
}上面,我们在控制台中显示了一条消息,如果用户选择“是”按钮。以下是一个示例,让 JOptionPane 处理“是”、“否”和“关闭”按钮 –
示例
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!");
}
}
}输出

假设你选择了上面的“是”。这种情况,控制台中会看到如下内容 –

假设你选择了上面的“否”。这种情况,控制台中会看到如下内容 –

假设你按了上面的“取消”(关闭)。这种情况,控制台中会看到如下内容 –

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP