JOptionPane:Java 对话框 showOptionDialog
java.swing.JOptionPane 类中的另一种类型的对话框是 OptionDialog。它可以显示多个按钮、一条消息或一组 JButton 组件。这可以通过以下方法完成:showOptionDialog(frame, message, title, typeOption, typeMessage 图标选项default),或者:
- frame:是父组件;
- message:是要在对话框中显示的字符串消息;
- title:用作对话框的标题;
- typeOption:是一个整数,表示对话框中的选项类型。有效代码为:YES_NO_OPTION,YES_NO_CANCEL_OPTION,OK_CANCEL_OPTION跨度>;
- typeMessage: 是一个整数,表示在 JOptionPane: classINFORMATION_MESSAGE、WARNING_MESSAGE、ERROR_MESSAGE和PLAIN_MESSAGE跨度>;
- icon:是要显示的 ImageIcon 图标;
- 选项;是用户可以执行的选择表;
- default或 initialvalue 是要选择的缺省值。
此代码示例实现一个对话框,其中包含 options:
import javax.swing.JOptionPane;
public class OptionDialog {
public static void main(String[] args) {
int return = JOptionPane.showOptionDialog(null,
你确定要继续吗?”,
错误”,
//JOptionPane 是 no
JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE,
null, null, null);
}
}
运行程序后,您将看到此对话框,其中包含错误消息和两个是”和否”选项按钮。您可以安排事件,例如,当您单击否”按钮时,您将退出程序。
References:
herongyang: showOptionDialog() - 显示选项对话框
Java 文档:showOptionDialog 方法
System.exit(
0
)
:控制 JOptionPane.showOptionDialog 中的按钮
如果要添加按钮或更改值,可以通过添加对象数组作为选项并选择默认选择的初始值来实现。import javax.swing.JOptionPane;Result:
public class OptionDialog {
public static void main(String[] args) {
Object[] choice={18-25 years”,26-35 years”,36-45 years”,46-55 years”,56 years and older”};
int choice = JOptionPane.showOptionDialog(null,
你的年龄范围是多少?”,
年龄范围”,
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, choice, choice[0]);
}
}
References:
herongyang: showOptionDialog() - 显示选项对话框
Java 文档:showOptionDialog 方法