简体   繁体   English

Java Swing应用程序生命周期问题

[英]Java Swing application lifecycle problem

I have a Java application which is used to start a Swing user interface. 我有一个Java应用程序,用于启动Swing用户界面。 The interface is a class with an encapsulated JFrame instance. 接口是带有封装的JFrame实例的类。 The problem is that the application allocates some resources and the Swing interface uses these resources, but the application closes the resource not the user interface. 问题在于,应用程序分配了一些资源,而Swing界面使用了这些资源,但是应用程序关闭了资源, 而不是用户界面。

How can I achieve either the main application gets a notification when the complete Swing interface is closed or that the start of the Swing interface blocks until it's closed. 当完整的Swing接口关闭时,如何实现主应用程序得到通知,或者直到关闭它为止,Swing接口的开始都会阻塞。 Closed means that the WindowAdapter.windowClosed(WindowEvent) method of the JFrame WindowListener was already invoked. 关闭表示JFrame WindowListener的WindowAdapter.windowClosed(WindowEvent)方法已被调用。

The solution from this thread ( link ) seems to return when the JFrame will be invisble, does this include the WINDOW_CLOSED event handling? 当JFrame不可见时,此线程( 链接 )的解决方案似乎返回,这是否包括WINDOW_CLOSED事件处理?

Edit: Maybe it will be a solution to implement this lifecycle interface: 编辑:也许它将是实现此生命周期接口的解决方案:

public interface Lifecycle {

    public void startup();

    public void shutdown();

}

Now the Swing interface class has to invoke the shutdown() method of the main application in the handler of the WindowEvent.WINDOW_CLOSED event. 现在,Swing接口类必须在WindowEvent.WINDOW_CLOSED事件的处理程序中调用主应用程序的shutdown()方法。

Is it possible and a good pratice to do so? 这样做是否可行并且是一个好习惯?

Try to use Toolkit.getDefaultToolkit().addAWTEventListener() . 尝试使用Toolkit.getDefaultToolkit().addAWTEventListener() If you supply appropriate event mask you can get events you need. 如果提供适当的事件掩码,则可以获取所需的事件。 This is without subscribing to specific instance of JFrame. 这无需订阅JFrame的特定实例。

The approach should be as follows 方法应如下

  • resource closing should raise an event 资源关闭应该引发一个事件
  • The class encapsulated the JFrame, should listen to the resource closing event 该类封装了JFrame,应该侦听资源关闭事件
  • and the listener should call the JFrame.setEnabled(false) method to make it disable 并且侦听器应调用JFrame.setEnabled(false)方法使其禁用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM