WindowListener用于关闭JFrame并使用全局变量 [英] WindowListener for closing JFrames and use global variable

查看:246
本文介绍了WindowListener用于关闭JFrame并使用全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使用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?

推荐答案

过去当我遇到同样的问题时,我决定实施一个< a href =http://en.wikipedia.org/wiki/Singleton_pattern =nofollow>单例模式,以保持用户当前会话的全局。通过这种方式,我可以访问我需要的任何类中的当前会话。

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

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

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

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

注意:此处调用此方法将执行事件调度线程导致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.

这篇关于WindowListener用于关闭JFrame并使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆