How to avoid JFrame EXIT_ON_CLOSE operation to exit the entire application?

送分小仙女□ 提交于 2019-12-23 12:01:37

问题


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.

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.

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 :(.


回答1:


if you want to close only the frame you see, it should be DISPOSE_ON_CLOSE

EDIT:

Try intercepting the EXIT_ON_CLOSE event.

frame.getGlassPane() or frame.getRootPane()

may be useful.

Also if you have right to execute methods of the other app, you can call setDefaultCloseOperation again setting it to DISPOSE_ON_CLOSE




回答2:


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!");
    }
}



回答3:


You can get list of all frames using Frame's static method public static Frame[] getFrames()

Iterate the list and check if a list member is instanceof JFrame change default close operation to DISPOSE_ON_CLOSE



来源:https://stackoverflow.com/questions/4827892/how-to-avoid-jframe-exit-on-close-operation-to-exit-the-entire-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!