setDefaultCloseOperation改为显示JFrame [英] setDefaultCloseOperation to show a JFrame instead
问题描述
我正在编写一个文字处理程序应用程序来练习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设置为捕获close事件并执行所需的操作.我将在几分钟后发布一个示例.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!