问题描述
我有一个可以启动其他应用程序的应用程序,例如扩展坞.问题是,如果我正在启动的应用程序(JFrame
)具有EXIT_ON_CLOSE
,它也会关闭我的主应用程序.
I have a application that launches other applications, something like a dock. The problem is that if the app that I'm launching (JFrame
) has the EXIT_ON_CLOSE
it will also close my main application.
我无法控制正在启动的应用程序.也就是说,我不能指望该应用程序具有良好的行为并使用DISPOSE_ON_CLOSE
.
I have no control what-so-ever over the applications that I'm launching. That is, I cannot expect the application to have a good behavior and use DISPOSE_ON_CLOSE
.
我该怎么做才能避免这种情况?我已经尝试过使用线程,但是没有运气.我还尝试将主应用程序线程放入守护程序中,但也没有运气.
What can I do to avoid this? I've tried already to use threads, but no luck. I also tried to put the main application thread in daemon, but no luck too.
我尝试放置一个自定义的SecurityManager
来覆盖checkExit
方法.问题在于,即使是主应用程序也无法退出.同样,它也不起作用,因为使用EXIT_ON_CLOSE
作为其默认关闭操作的应用程序将引发异常并且无法执行(因为Swing检查Security Manager的退出-System.checkExit()),因此无法启动:(.
I've tried putting a custom SecurityManager
overwritting the checkExit
method. The problem is that now even the main app can't exit. Also, it doesn`t "work" because applications that use EXIT_ON_CLOSE
as their default close operation will throw a Exception and not execute (since Swing checks the Security Manager for the exit -- System.checkExit()), failing to launch :(.
推荐答案
有点麻烦,但是您始终可以使用SecurityManager
来管理其他框架.
It is a bit of a hack, but you can always use a SecurityManager
to manage the other frames.
这个简单的示例可防止框架退出:
This simple example prevents a frame from exiting:
import java.awt.*;
import javax.swing.*;
public class PreventExitExample {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
PreventExitExample o = new PreventExitExample();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationByPlatform(true);
f.setSize(new Dimension(400,200));
f.setVisible(true);
System.setSecurityManager(new PreventExitSecurityManager());
}
};
SwingUtilities.invokeLater(r);
}
}
class PreventExitSecurityManager extends SecurityManager {
@Override
public void checkExit(int status) {
throw new SecurityException("Cannot exit this frame!");
}
}
这篇关于如何避免JFrame EXIT_ON_CLOSE操作退出整个应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!