Domanda

I'm struggling with using WindowListener for closing JFrames.

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?

È stato utile?

Soluzione

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.

It should be something like this:

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

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

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

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top