setDefaultCloseOperation to show a JFrame instead(setDefaultCloseOperation 改为显示 JFrame)
问题描述
为了练习 Java,我正在制作一个文字处理器应用程序,我希望这样当用户尝试关闭应用程序时,会出现一个 JFrame,要求保存更改.
I am making a word processor application in order to practise Java and I would like it so that when the user attempts to close the appliction, a JFrame will come up asking to save changes.
我正在考虑 setDefaultCloseOperation() 但到目前为止我运气不佳.如果可能的话,我也希望它在用户单击窗口右上角的X"时出现.
I was thinking about setDefaultCloseOperation() but I have had little luck so far. I would also like it to appear whent he user clicks the "X" on the top right of the window aswell if possible.
推荐答案
您可以将 JFrame DefaultCloseOperation 设置为 DO_NOTHING 之类的东西,然后设置一个 WindowsListener 来获取关闭事件并执行您想要的操作.我会在几分钟后发布一个示例.
You can set the JFrame DefaultCloseOperation to something like DO_NOTHING, and then, set a WindowsListener to grab the close event and do what you want. I'll post an exemple in a few minutes .
这是示例:
public static void main(String[] args) {
final JFrame frame = new JFrame("Test Frame");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setSize(800, 600);
frame.addWindowListener(new WindowAdapter() {
//I skipped unused callbacks for readability
@Override
public void windowClosing(WindowEvent e) {
if(JOptionPane.showConfirmDialog(frame, "Are you sure ?") == JOptionPane.OK_OPTION){
frame.setVisible(false);
frame.dispose();
}
}
});
frame.setVisible(true);
}
这篇关于setDefaultCloseOperation 改为显示 JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:setDefaultCloseOperation 改为显示 JFrame


基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01