JFrame关闭按钮的弹出窗口 [英] Popup for JFrame close button
问题描述
我正在做一些基本的Java Swing application
(初学者级别).
我要做的是当我按下close button on JFrame
来结束窗口时,我想要的是JOptionPane Confirm Dialog
而不是直接关闭
i am doing some basic Java Swing application
(beginner level) .
what i have to do is when i press close button on JFrame
to colse the window i want a JOptionPane Confirm Dialog
instead of straightforward close
这是代码JFrame
here is the code JFrame
JFrame frame= new JFrame("frame");
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
和JOptionPane代码像这样
and JOptionPane code goes like this
final JOptionPane optionPane = new JOptionPane("Are You sure?",JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
因此,当按下JFrame上的关闭"按钮时,应该弹出此弹出窗口,而不是直接关闭
请指导我我该怎么做..预先感谢
so when Close button on JFrame pressed this popup should come up instead of Direct closing
Please guide me how i can do it .. Thanks in advance
推荐答案
您可以按照以下步骤操作:
You can do it by following steps:
-
将
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
行替换为frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
实施WindowListener
并覆盖其所有抽象方法.您可以在此处查找.
Implement WindowListener
and override its all abstract methods. You can find it here.
以这种方式覆盖public void windowClosing(WindowEvent e)
方法:
@Override
public void windowClosing(WindowEvent e){
int result = JOptionPane.showConfirmDialog(null, "Are you sure,"Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if(result == JOptionPane.YES_OPTION){
System.exit(0);
}else{
//Do nothing
}
}
这篇关于JFrame关闭按钮的弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!