调用方法应用程序关闭时 [英] Call a method when application closes
本文介绍了调用方法应用程序关闭时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的挥杆聊天应用程序,我有一个用于注销用户注销按钮,它工作正常。现在我需要当我关闭Swing应用程序窗口注销用户。
In my Swing chat application I have a logout button which is used to logout the user and it works fine. Now I need to logout the user when I close the Swing application window.
我在Web应用程序中关闭使用JavaScript的浏览器的时候这样做,但现在我需要做的这Swing应用程序。
I did this in web application when closing browser using JavaScript, but now I need to do this in Swing application.
我怎样才能做到这一点?
How can I achieve this?
推荐答案
- 呼叫
JFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
- 添加
的WindowListener
到框架上。 - 覆盖听者的适当的方法叫你收方法,然后设置帧无形处置。
例如
import java.awt.*;
import java.awt.event.*;
import java.net.URI;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class CheckExit {
public static void doSomething() {
try {
// do something irritating..
URI uri = new URI(
"http://stackoverflow.com/users/418556/andrew-thompson");
Desktop.getDesktop().browse(uri);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
@Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new BorderLayout());
gui.setPreferredSize(new Dimension(400, 100));
gui.setBackground(Color.WHITE);
final JFrame f = new JFrame("Demo");
f.setLocationByPlatform(true);
f.add(gui);
// Tell the frame to 'do nothing'.
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
WindowListener listener = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
int result = JOptionPane.showConfirmDialog(
f, "Close the application");
if (result==JOptionPane.OK_OPTION) {
doSomething();
f.setVisible(false);
f.dispose();
}
}
};
f.addWindowListener(listener);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
这篇关于调用方法应用程序关闭时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文