WindowListener 用于关闭 JFrames 并使用全局变量

我正在努力使用 WindowListener 来关闭 JFrame.

I'm struggling with using WindowListener for closing JFrames.

我有一个客户端登录到服务器的情况,当客户端关闭他的应用程序时,需要通知服务器.因此,为了通知服务器,应该处理一个类的另一个实例(处理 rmi 实现).该实例是我的 GUI 类中的全局变量.

I have a situation where a client is logged on to a server and when the client closes his application the server needs to be informed. So in order to inform the server, another instance of a class (that handles the rmi implementation) should be addressed. that instance is a global variable in my GUI class.

我在网上搜索了一下,但我能解决的问题是以下结构

I searched the web a bit but all i can fined to the problem is the following structure

addWindowListener(new WindowAdapter() 
{
  public void windowClosed(WindowEvent e)
  {
    System.out.println("jdialog window closed event received");
  }

  public void windowClosing(WindowEvent e)
  {
    System.out.println("jdialog window closing event received");
  }
});

这里的问题是我不能使用全局变量.谁能帮我解决这个问题?

the problem here is that i can't use a global variable. anybody who can help me with this problem?

推荐答案

过去当我遇到同样的问题时,我决定实现一个 单例模式 保持用户当前会话全局".这样我就可以访问我需要的任何课程中的当前会话.

In the past when I faced the same issue, I decided to implement a Singleton pattern to keep the user's current session "global". This way I have access to the current session in any class I need.

应该是这样的:

public class SessionManager {

    private static SessionManager instance;
    private Session currentSession; // this object holds the session data (user, host, start time, etc)

    private SessionManager(){ ... }

    public static SessionManager getInstance(){
        if(instance == null){
            instance = new SessionManager();
        }
        return instance;
    }

    public void startNewSession(User user){
        // starts a new session for the given User
    }

    public void endCurrentSession(){
        // here notify the server that the session is being closed
    }

    public Session getCurrentSession(){
        return currentSession;
    }
}

然后我在 windowClosing() 方法中调用 endCurrentSession(),如下所示:

Then I call endCurrentSession() inside windowClosing() method, like this:

public void windowClosing(WindowEvent e) {
    SessionManager.getInstance().endCurrentSession();
}

注意:这里调用这个方法会在Event Dispatch Thread 导致 GUI冻结",直到此方法完成.如果您与服务器的交互需要很长时间,您可能希望在单独的线程中进行.

Note: calling this method here will execute in the Event Dispatch Thread causing GUI "freezes" until this method is done. If your interaction with the server takes a long time, you'd want to make this in a separate thread.

相关文章