在我的 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);
}
}
这将完成工作