Java: Preventing a child window’s close operation from exiting the app.

I included a second JFrame in NetBeans, which I used as a child window. When the child window was closed, all windows were closed. I finally figured out that the default close operation needed to be either HIDE_ON_CLOSE or DISPOSE_ON_CLOSE. The default in Java is HIDE_ON_CLOSE, but in NetBeans is EXIT_ON_CLOSE.

I first changed this property in the main window code that invokes the child window, but then I looked at the Properties page for the child window. “defaultCloseOperation” is the first property. “DISPOSE” can be selected here.

From Sun Java Documentation

setDefaultCloseOperation

public void setDefaultCloseOperation(int operation)
Sets the operation that will happen by default when the user initiates a “close” on this frame. You must specify one of the following choices:

  • DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don’t do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.
  • HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any registered WindowListener objects.
  • DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the frame after invoking any registered WindowListener objects.
  • EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.

The value is set to HIDE_ON_CLOSE by default.