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);
}
相关文章