0

two JFrames,

JFrame Main; // Main JFrame

JFrame Sub; //Second JFrame that is initialized from within Main via a JMenuItems ActionListener.

mainMenuItem.setActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent arg0) {
        try{
            Sub subFrame = new Sub();
            subFrame.setVisible(true);
        }catch(Exception e){}
        }
    });
}

The problem is whenever i close the second JFrame (Sub) it closes the first aswell.

Both JFrames have:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Is that part of the problem?

jzd
  • 23,473
  • 9
  • 54
  • 76
Eduardo
  • 6,900
  • 17
  • 77
  • 121

3 Answers3

5

EXIT_ON_CLOSE means to exit the program immediately (System.exit()) when the frame is closed.

You probably want to set this to DISPOSE_ON_CLOSE, then add a WindowListener and close the program only if both frames have been closed.

(Or, perhaps you want only the main frame to have EXIT_ON_CLOSE)

Russell Zahniser
  • 16,188
  • 39
  • 30
3

Yes. JFrame.EXIT_ON_CLOSE by definition exits the application. For your second Frame use DISPOSE_ON_CLOSE or HIDE_ON_CLOSE.

Hope this helps!

Mechkov
  • 4,294
  • 1
  • 17
  • 25
2

You state:

JFrame Sub; //Second JFrame that is initialized from within Main via a JMenuItems ActionListener.

This suggests you've a design problem:

  • Your 2nd "frame" shouldn't even be a JFrame since it is not behaving as a separate independent main program window.
  • Instead it's acting as a dialog since it is dependent on and shown from a parent window, the main JFrame. So make the secondary window a JDialog not a JFrame, and all these problems will go away.
  • You will need to consider whether it should be a modal dialog where the main window is not accessable to the user while the dialog is open, or a non-modal dialog.
  • Having said that, you may even be better off using one window/JFrame and swapping views via a CardLayout.

Please read this link: The Use of Multiple JFrames, Good/Bad Practice?, and in particular please have a look at Andrew Thompson's community wiki answer.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thanks, i didnt realise it was bad practice to have multiple JFrames. I just want a pop up window with some text like the "about" window that most software contains where you see the version number etc. What would be a better way of doing this without another JFrame? – Eduardo Oct 21 '13 at 17:31
  • @clairharrison: again what you are trying to do is show a dialog window. The standard way to do this is as I describe above in my answer. – Hovercraft Full Of Eels Oct 21 '13 at 18:13