WindowListener for closing JFrames and use global variable(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.
这篇关于WindowListener 用于关闭 JFrames 并使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:WindowListener 用于关闭 JFrames 并使用全局变量
基础教程推荐
- 在螺旋中写一个字符串 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01