Popup for JFrame close button(JFrame 关闭按钮的弹出窗口)
问题描述
我正在做一些基本的 Java Swing 应用程序(初级).我要做的是当我按下 JFrame 上的 close 按钮 来关闭我想要一个 JOptionPane 确认对话框 而不是直接关闭的窗口时
i am doing some basic Java Swing application (beginner level) .
what i have to do is when i press close button on JFrame to colse the window i want a JOptionPane Confirm Dialog instead of straightforward close
这里是代码 JFrame
here is the code JFrame
JFrame frame= new JFrame("frame");
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
JOptionPane 代码是这样的
and JOptionPane code goes like this
final JOptionPane optionPane = new JOptionPane("Are You sure?",JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
所以当按下 JFrame 上的关闭按钮时,这个弹出窗口应该出现而不是直接关闭
请指导我如何做到这一点..提前谢谢
so when Close button on JFrame pressed this popup should come up instead of Direct closing
Please guide me how i can do it .. Thanks in advance
推荐答案
您可以按照以下步骤进行:
You can do it by following steps:
将
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);行替换为frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
实现 WindowListener 并覆盖其所有抽象方法.您可以在这里找到它.
Implement WindowListener and override its all abstract methods. You can find it here.
以这种方式覆盖 public void windowClosing(WindowEvent e) 方法:
Override the public void windowClosing(WindowEvent e) method some this way:
@Override
public void windowClosing(WindowEvent e){
int result = JOptionPane.showConfirmDialog(null, "Are you sure,"Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if(result == JOptionPane.YES_OPTION){
System.exit(0);
}else{
//Do nothing
}
}
这篇关于JFrame 关闭按钮的弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JFrame 关闭按钮的弹出窗口
基础教程推荐
- 在springboot中如何给mybatis加拦截器 2023-04-29
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
