如何捕获JFrame的关闭按钮单击事件? [英] How to capture a JFrame's close button click event?
本文介绍了如何捕获JFrame的关闭按钮单击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当点击JFrame标题栏的红色关闭按钮时,我想调用方法 confirmExit()
。
I want to call a method confirmExit()
when the red close button of the title bar of a JFrame is clicked.
如何捕获该事件?
如果用户选择不继续,我还想阻止窗口关闭。
I'd also like to prevent the window from closing if the user chooses not to proceed.
推荐答案
import javax.swing.JOptionPane;
import javax.swing.JFrame;
/*Some piece of code*/
frame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
if (JOptionPane.showConfirmDialog(frame,
"Are you sure you want to close this window?", "Close Window?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
如果您还想阻止窗口关闭,除非用户选择是,您可以添加:
If you also want to prevent the window from closing unless the user chooses 'Yes', you can add:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
这篇关于如何捕获JFrame的关闭按钮单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文