Java Swing 为 EXIT_ON_CLOSE 添加动作监听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16295942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Swing adding Action Listener for EXIT_ON_CLOSE
提问by Sam
I have a simple GUI:
我有一个简单的 GUI:
public class MyGUI extends JFrame{
public MyGUI(){
run();
}
void run(){
setSize(100, 100);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// maybe an action listener here
}
}
I would like to print out this message:
我想打印出这条消息:
System.out.println("Closed");
When the GUI is closed (when the X is pressed). How can I do that?
当 GUI 关闭时(按下 X 时)。我怎样才能做到这一点?
采纳答案by prasanth
Try this.
尝试这个。
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
System.out.println("Closed");
e.getWindow().dispose();
}
});
回答by Mr Tsjolder
Another possibility could be to override dispose()
from the Window
class. This reduces the number of messages sent around and also works if the default close operation is set to DISPOSE_ON_CLOSE
.
另一种可能性是dispose()
从Window
类中覆盖。这减少了发送的消息数量,并且如果默认关闭操作设置为DISPOSE_ON_CLOSE
.
Concretely this means adding
具体来说,这意味着添加
@Override
public void dispose() {
System.out.println("Closed");
super.dispose();
}
to your class MyGUI
.
到你的班级MyGUI
。
Note: don't forget to call super.dispose()
as this releases the screen resources!
注意:不要忘记调用,super.dispose()
因为这会释放屏幕资源!
回答by ersks
Write this code within constructor of your JFrame:
在JFrame 的构造函数中编写此代码:
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.out.println("Uncomment following to open another window!");
//MainPage m = new MainPage();
//m.setVisible(true);
e.getWindow().dispose();
System.out.println("JFrame Closed!");
}
});
回答by Ashraf Gardizy
Window Events:There is the complete program, hope it will help you. public class FirstGUIApplication {
Window Events:有完整的程序,希望对你有帮助。公共类 FirstGUIApplication {
public static void main(String[] args) {
//Frame
JFrame window = new JFrame();
//Title:setTitle()
window.setTitle("First GUI App");
//Size: setSize(width, height)
window.setSize(600, 300);
//Show: setVisible()
window.setVisible(true);
//Close
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
JOptionPane.showConfirmDialog(null,"Are sure to close!");
}
@Override
public void windowOpened(WindowEvent e) {
super.windowOpened(e);
JOptionPane.showMessageDialog(null, "Welcome to the System");
}
});
}
}
}