我正在使用套接字在聊天客户端上工作,并且我希望在用户单击“X”时窗口关闭之前执行某些代码(例如正确关闭连接)。
我可以在不必实现所有抽象方法的情况下做到这一点WindowListener
吗?
/阿文
只是扩展 WindowAdapter
,而不是实施 WindowListener
。
您会在所有 Swing 听众身上找到这个概念。( MouseListener/MouseAdapter
, KeyListener/KeyAdapter
, ...) 有一个Listener
接口和一个Adapter
用空方法实现该接口的类。
因此,如果您只想对特定事件做出反应,请使用适配器并覆盖所需的方法。
例子:
setWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
//Cleanup code
}
});
这是你需要的
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);}
}
}
如何ExitListener
从 a中添加 an 的示例FrameView
:
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;
}
}