[英]Call a method when application closes
在我的Swing聊天應用程序中,我有一個注銷按鈕,該按鈕用於注銷用戶,並且工作正常。 現在,當我關閉Swing應用程序窗口時,需要注銷用戶。
當使用JavaScript關閉瀏覽器時,我在Web應用程序中執行了此操作,但是現在我需要在Swing應用程序中執行此操作。
我該如何實現?
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);
}
}
使用JFrame上的窗口事件,例如,那里有您可能需要的方法(windowclosed();)。 這是WindowListener
編輯:
你可以說
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
但是如果您按X(關閉按鈕),則Windowlistener仍然可以工作
在那里,您使用此代碼覆蓋了方法windowClosing
public void windowClosing(WindowEvent e) {
int i = JOptionPane.showConfirmDialog(TestFrame.this, "do you really want to close?","test",JOptionPane.YES_NO_OPTION);
if(i == 0) {
System.exit(0);
}
}
這會做的工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.