在JFrame中,窗体右上角的小红叉默认点击就是关闭窗体,如果frame窗体和showConfirmDialog对话框创建一个联系:
当点击frame小红叉时,弹出对话框(是否关闭窗口?),点击对话框按钮后,对话框关闭,而frame不关闭!
就是在当前窗口的构造函数添加一句话:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
代码如下:
1 package Test; 2 3 import java.awt.event.WindowAdapter; 4 import java.awt.event.WindowEvent; 5 import javax.swing.JFrame; 6 import javax.swing.JOptionPane; 7 8 public class Demo { 9 private JFrame frame; 10 11 public static void main(String[] args) { 12 Demo window = new Demo(); 13 window.frame.addWindowListener(new WindowAdapter() { 14 public void windowClosing(WindowEvent e) { 15 int i= JOptionPane.showConfirmDialog(null, "确认退出吗?"); 16 if(i==JOptionPane.OK_OPTION){ 17 System.exit(0); 18 }else{ 19 20 } 21 } 22 }); 23 } 24 25 public Demo() { 26 initialize(); 27 } 28 29 private void initialize() { 30 frame = new JFrame(); 31 frame.setBounds(100, 100, 450, 300); 32 // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//默认点击关闭 33 frame.setVisible(true); 34 frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 35 } 36 }
截图如下: