packagecom.siwuxie095.showdialog;
importjava.awt.BorderLayout;
importjava.awt.EventQueue;
importjavax.swing.JFrame;
importjavax.swing.JOptionPane;
importjavax.swing.JPanel;
importjavax.swing.UIManager;
importjavax.swing.UnsupportedLookAndFeelException;
importjavax.swing.border.EmptyBorder;
importcom.sun.java.swing.plaf.windows.WindowsLookAndFeel;
importjavax.swing.JButton;
importjava.awt.event.MouseAdapter;
importjava.awt.event.MouseEvent;
public classTestConfirmDialog extendsJFrame {
privateJPanel contentPane;
/**
* Launch the application.
*/
public staticvoidmain(String[] args) {
EventQueue.invokeLater(newRunnable() {
publicvoidrun() {
try{
TestConfirmDialog frame = newTestConfirmDialog();
frame.setVisible(true);
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
publicTestConfirmDialog() {
try{
UIManager.setLookAndFeel(newWindowsLookAndFeel());
} catch(UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = newJPanel();
contentPane.setBorder(newEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(newBorderLayout(0, 0));
setContentPane(contentPane);
JButton btnshowconfirmdialog = newJButton("显示确认框(showConfirmDialog)");
//为按钮添加鼠标点击事件
btnshowconfirmdialog.addMouseListener(newMouseAdapter() {
@Override
publicvoidmouseClicked(MouseEvent e) {
//直接通过静态方法调用,指定父级窗体和信息
//返回值是int类型,创建以接收返回值
//没有关闭确认框时,后面的主窗体是完全无法操作的(即阻塞)
// int value=JOptionPane.showConfirmDialog(TestConfirmDialog.this,
// "你确认退出吗?");
//
// if (value==JOptionPane.YES_OPTION) {
// System.out.println("你选择了是");
// System.exit(0);
// }else if (value==JOptionPane.NO_OPTION) {
// System.out.println("你选择了否");
// }else if (value==JOptionPane.CANCEL_OPTION) {
// System.out.println("你选择了取消");
// }else if (value==JOptionPane.CLOSED_OPTION) {
// System.out.println("你直接将窗体关闭了,没有选择");
// }
//需要指定父级窗体,信息,标题,选项类型,信息类型
intvaluex=JOptionPane.showConfirmDialog(TestConfirmDialog.this,
"你确认要退出程序吗?", "请确认",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
//判断时要根据第四个参数optionType
//可以选择一个最有用的按钮来判断它的值并处理即可,不用全部都判断
if(valuex==JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
btnshowconfirmdialog.setFocusable(false);
contentPane.add(btnshowconfirmdialog, BorderLayout.NORTH);
}
}