java中如何实现当点击Frame框右上角那个×时自动询问“是否退出”?
展开全部
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Test extends JFrame {
public Test(){
this.setTitle("title");
this.setSize(300,200);
this.setLocation(100,100);
//设置关闭时什么也不做
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
//监听关闭按钮的点击操作
this.addWindowListener(new WindowAdapter(){
//new 一个WindowAdapter 类 重写windowClosing方法
//WindowAdapter是个适配器类 具体看jdk的帮助文档
public void windowClosing(WindowEvent e) {
//这里写对话框
if(JOptionPane.showConfirmDialog(null, "退出","提示",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE)==JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
this.setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Test extends JFrame {
public Test(){
this.setTitle("title");
this.setSize(300,200);
this.setLocation(100,100);
//设置关闭时什么也不做
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
//监听关闭按钮的点击操作
this.addWindowListener(new WindowAdapter(){
//new 一个WindowAdapter 类 重写windowClosing方法
//WindowAdapter是个适配器类 具体看jdk的帮助文档
public void windowClosing(WindowEvent e) {
//这里写对话框
if(JOptionPane.showConfirmDialog(null, "退出","提示",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE)==JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
this.setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询