【问题标题】:How to use something other than the DefaultClosingOperation when closing a JFrame window?关闭 JFrame 窗口时如何使用 DefaultClosingOperation 以外的其他内容?
【发布时间】:2009-05-03 09:12:05
【问题描述】:

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

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

/阿文

【问题讨论】:

    标签: java events jframe listeners


    【解决方案1】:

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

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

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

    示例:

    setWindowListener(new WindowAdapter() {
        public void windowClosed(WindowEvent e) {
            //Cleanup code
        }
    });
    

    【讨论】:

      【解决方案2】:

      这是你需要的

      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);}
      }
      }
      

      【讨论】:

        【解决方案3】:

        如何在FrameView 中添加ExitListener 的示例:

        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;
                 }
        }
        

        【讨论】:

          猜你喜欢
          • 2023-01-24
          • 1970-01-01
          • 2013-06-27
          • 1970-01-01
          • 1970-01-01
          • 2012-11-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多