这意味着您正在使用安全管理器:
SecurityException – if a security manager exists and it denies the AWTPermission(“showWindowWithoutWarningBanner”) permission, or the calling thread is not allowed to create a subprocess; and not invoked from within an applet or Java Web Started application
如果这是applet或Java Web Start应用程序 – 请在jar上签名.
更新添加安全管理器以检测程序退出是错误的.有多种方法可以正确地完成这项工作.在你的情况下,我想这是最合适的:
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
closeFile();
}
));
Swing特定的解决方案是:
>如果您不必执行额外操作,请使用frame.setDefaultCloseAction(Frame.EXIT_ON_CLOSE)
>使用addWindowStateListener并检查WindowEvent.WINDOW_CLOSED
那说,两个说明:
>你不能长时间保持文件打开状态.使用try / catch / finally可以在需要时打开和关闭它们.
>如果您确实需要某个安全管理器,请确保覆盖SecurityManager的相应方法,以检查您是否可以打开该链接. (不会告诉你哪一个,所以你不要试图跳到这个解决方案,这是错误的)
总而言之,我会选择setDefaultActionOnClose,并在读完/写完后立即关闭每个文件.
更新2:在您链接到原始问题后,描述了您想要实现的目标,事情会有所改变.您正试图阻止退出,因此您确实需要一个SecurityManager.这使得你应该覆盖checkPermission方法并在那里什么都不做(即不抛出异常),至少在检查这些权限时(在调用browse时检查它们):
>新的AWTPermission(“showWindowWithoutWarningBanner”)
> new FilePermission(“<>”,SecurityConstants.FILE_EXECUTE_ACTION)
更新3以下是如何完全覆盖该方法:
@Override
public void checkPermission(Permission permission) {
if (permission instanceof AWTPermission) {
if (permission.getName().equals("showWindowWithoutWarningBanner")) {
return;
}
}
if (permission instanceof FilePermission) {
if (permission.getActions().equalsIgnoreCase("execute")) {
return;
}
}
java.security.AccessController.checkPermission(permission);
}
(你可以没有外面的if-s)
更新4只有在您授予程序权限的情况下,上述方法才有效.否则,JVM的一个记录不明确的行为是不允许覆盖安全管理器的非特权.看看this report – 评论说如何解决它.
为了简化您的生活,您可以使用空方法体@Override public void checkPermission(..).