Optional way to close a dialog window

后端 未结 3 1103
太阳男子
太阳男子 2021-01-28 03:46

I\'m using a custom JFrame to implement a simple dialog in a Java application I\'m working on.

After the user pushes the \'Apply\' button in the window, it should close.

3条回答
  •  梦谈多话
    2021-01-28 04:26

    To close a window in Swing like JFrame or JDialog you have two options.

    Call dispose()

    Just call dispose() method:

    public void dispose()
    

    Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable.

    For instance:

    frame.dispose();
    dialog.dispose();
    

    Dispatch a WINDOW_CLOSING event

    You can dispatch a new WindowEvent like this:

    frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
    dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING));
    

    If the window has attached a WindowListener it will be notified. If the frame's (or dialog's) default close operation is set then this action will be performed. The possible close operations are:

    • 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 and not available for JDialog): Exit the application using the System exit method. Use this only in applications.

提交回复
热议问题