对话框概述
swing中的JOptionPane类提供了创建对话框的方法
创建方法支持重载,说明如下
对话框的返回值
showConfirmDialog的返回值有如下几个:
程序实例
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MessageShow {
JFrame jf=new JFrame();
private void init(){
jf.setLayout(new FlowLayout());
jf.setBounds(200,50,500,400);
JButton btnOpen = new JButton("弹出对话框");
btnOpen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//消息对话框
// JOptionPane.showMessageDialog(jf, "显示内容", "显示标题",JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(jf, "显示内容", "显示标题",JOptionPane.INFORMATION_MESSAGE);
// JOptionPane.showMessageDialog(jf, "显示内容", "显示标题",JOptionPane.WARNING_MESSAGE);
// JOptionPane.showMessageDialog(jf, "显示内容", "显示标题",JOptionPane.QUESTION_MESSAGE);
// JOptionPane.showMessageDialog(jf, "显示内容", "显示标题",JOptionPane.PLAIN_MESSAGE);
//确认对话框
// int result = JOptionPane.showConfirmDialog(jf, "显示内容", "显示标题", JOptionPane.DEFAULT_OPTION);
int result = JOptionPane.showConfirmDialog(jf, "显示内容", "显示标题", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
if(result==JOptionPane.YES_OPTION){
System.out.println("用户确定了");
}
if(result==JOptionPane.NO_OPTION){
System.out.println("用户取消了");
}
//输入对话框
String input = JOptionPane.showInputDialog(jf, "请输入账号:", "输入对话框", JOptionPane.INFORMATION_MESSAGE);
System.out.println(input);
//选项对话框
int index = JOptionPane.showOptionDialog(jf, "请选择合适尺寸:", "选择对话框", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null,
new String[]{"S", "M", "L", "XL"}, "M");
System.out.println(index);
}
});
jf.add(btnOpen);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
public static void main(String[] args) {
new MessageShow().init();
}
}
结果截图如下:
消息对话框截图:
确认对话框截图
输入对话框
选项对话框