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 @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
