如何在关闭JFrame窗口时使用DefaultClosingOperation以外的内容?
问题描述:
我正在使用一个套接字在聊天客户端上工作,并且我希望在用户单击“X”(如正确关闭连接)时在窗口关闭之前执行某个代码。如何在关闭JFrame窗口时使用DefaultClosingOperation以外的内容?
我可以这样做,而不必实现WindowListener
中的所有抽象方法吗?
/AVIN
答
只是延长WindowAdapter
,而不是实施WindowListener
。
你会发现这个概念在所有的Swing听众。 (MouseListener/MouseAdapter
,KeyListener/KeyAdapter
,...)有一个Listener
接口和一个Adapter
类,它用空方法实现这个接口。
因此,如果您只想对特定事件做出反应,请使用适配器并覆盖所需的方法。
例子:
setWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
//Cleanup code
}
});
答
这里是你需要的是如何从内FrameView
添加ExitListener
private class Closer extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
int exit = JOptionPane.showConfirmDialog(this, "Are you
sure?");
if (exit == JOptionPane.YES_OPTION) {
System.exit(0);}
}
}
答
例子:
YourApp.getApplication().addExitListener(new ExitListener() {
@Override
public boolean canExit(EventObject arg0) {
doStuff();
// the return value is used by the application to actually exit or
// not. Returning false would prevent the application from exiting.
return true;
}
}
这似乎是工作精细。非常感谢。 – Aveen 2009-05-03 09:43:20