2

我正在使用套接字在聊天客户端上工作,并且我希望在用户单击“X”时窗口关闭之前执行某些代码(例如正确关闭连接)。

我可以在不必实现所有抽象方法的情况下做到这一点WindowListener吗?

/阿文

4

3 回答 3

3

只是扩展 WindowAdapter,而不是实施 WindowListener

您会在所有 Swing 听众身上找到这个概念。( MouseListener/MouseAdapter, KeyListener/KeyAdapter, ...) 有一个Listener接口和一个Adapter用空方法实现该接口的类。

因此,如果您只想对特定事件做出反应,请使用适配器并覆盖所需的方法。

例子:

setWindowListener(new WindowAdapter() {
    public void windowClosed(WindowEvent e) {
        //Cleanup code
    }
});
于 2009-05-03T09:14:39.047 回答
1

这是你需要的

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);}
}
}
于 2009-05-03T09:18:54.480 回答
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;
         }
}
于 2009-05-03T14:02:06.890 回答