3

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

Marcos Roriz Junior
  • 4,076
  • 11
  • 51
  • 76

3 Answers3

3

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

fmucar
  • 14,361
  • 2
  • 45
  • 50
3

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!");
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

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

StanislavL
  • 56,971
  • 9
  • 68
  • 98