Java jframe exit on close

Содержание
  1. How to Exit JFrame on Close in Java Swing
  2. Exit JFrame on Close in Java Swing
  3. Creating a Java JFrame
  4. Two Approaches on Closing JFrame
  5. Java jframe exit on close
  6. Nested Class Summary
  7. Nested classes/interfaces inherited from class java.awt.Frame
  8. Nested classes/interfaces inherited from class java.awt.Window
  9. Nested classes/interfaces inherited from class java.awt.Container
  10. Nested classes/interfaces inherited from class java.awt.Component
  11. Field Summary
  12. Fields inherited from class java.awt.Frame
  13. Fields inherited from class java.awt.Component
  14. Fields inherited from interface javax.swing.WindowConstants
  15. Fields inherited from interface java.awt.image.ImageObserver
  16. Constructor Summary
  17. Method Summary
  18. Methods inherited from class java.awt.Frame
  19. Methods inherited from class java.awt.Window
  20. Methods inherited from class java.awt.Container
  21. Methods inherited from class java.awt.Component
  22. Methods inherited from class java.lang.Object
  23. Methods inherited from interface java.awt.MenuContainer
  24. Field Detail
  25. EXIT_ON_CLOSE
  26. rootPane
  27. rootPaneCheckingEnabled
  28. accessibleContext
  29. Constructor Detail
  30. JFrame
  31. JFrame
  32. JFrame
  33. JFrame
  34. Method Detail
  35. frameInit
  36. createRootPane
  37. processWindowEvent
  38. setDefaultCloseOperation
  39. getDefaultCloseOperation
  40. setTransferHandler
  41. getTransferHandler
  42. update
  43. setJMenuBar
  44. getJMenuBar
  45. isRootPaneCheckingEnabled
  46. setRootPaneCheckingEnabled
  47. addImpl
  48. remove
  49. setLayout
  50. getRootPane
  51. setRootPane
  52. setIconImage
  53. getContentPane
  54. setContentPane
  55. getLayeredPane
  56. setLayeredPane
  57. getGlassPane
  58. setGlassPane
  59. getGraphics
  60. repaint
  61. setDefaultLookAndFeelDecorated
  62. isDefaultLookAndFeelDecorated
  63. paramString
  64. getAccessibleContext

How to Exit JFrame on Close in Java Swing

In this tutorial, we will focus on learning how to exit JFrame on close in Java Swing. I will be discussing various methods in this tutorial in detail.

Exit JFrame on Close in Java Swing

We need to use the Java Swing library to create a JFrame, thus we must first import the library into our code. The Java Swing Library is used to create window-based applications with various powerful components such as JFrame which we will be using to create a frame.

Do read this article, which clearly explains the Java Swing Library, its components such as JLabel, the creation of a JFrame, inbuilt- methods, its parameters, etc.

Читайте также:  File open methods in java

Creating a Java JFrame

JFrame is a class of the javax.swing package which is a container that provides a window on the screen. We create a JFrame with the title “Exit on Close Example” and use the setVisible(true) function to display the frame. We specify the location of the frame using the setBounds() function.

Let’s see the code:

JFrame frame = new JFrame("Exit on Close Example"); // Creation of a new JFrame with the title frame.setVisible(true); // To display the frame frame.setBounds(100, 200, 350, 200); // To set the bounds of the frame.

How to Exit JFrame on Close in Java Swing

We have created a plain empty JFrame with our title successfully. Now, we have to exit JFrame on close. One simple way of doing this is clicking the cross button on the top right corner of the frame which closes the frame but the application or code will still be running in the background.

The efficient way of closing the JFrame is that we use the inbuilt method provided by the JFrame class i.e., using the JFrame.setDefaultCloseOperation(int) method. We use this method to change the behavior of the default JFrame which hides it instead of disposing of it when the user closes the window.

Two Approaches on Closing JFrame

Method 1: Using the WindowConstants

The simplest and most used technique is to use WindowConstants.EXIT_ON_CLOSE as a parameter. We must extend the JFrame class to our main class to use this. By using this, it closes the JFrame window completely and also frees the memory.

Method 2: Using the JFrame Constants

We have various constants defined by javax.swing.JFrame to close the JFrame as per our requirements. They are :

  • JFrame.EXIT_ON_CLOSE — A System.exit(0) will be executed which will exit the entire code and the frame.
  • JFrame.DISPOSE_ON_CLOSE — It will dispose of the frame but keep the code running.
  • JFrame.DO_NOTHING_ON_CLOSE — The frame will not be closed. It basically does nothing.
  • JFrame.HIDE_ON_CLOSE — This is the default one. It will hide the frame but keep the code running.

I have implemented both methods in the code for greater understanding.

Let’s see the code:

import javax.swing.*; public class ExitOnClose extends JFrame < public static void main(String[] args) < JFrame frame = new JFrame("Exit on Close Example"); // Creation of a new JFrame with the title frame.setLayout(null); // To position our components frame.setVisible(true); // To display the frame frame.setBounds(100, 200, 350, 200); // To set the locations of the frame. //------------------------------------------------ //To Terminate the JFrame and the code on close //------------------------------------------------ //METHOD-1 frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //METHOD-2 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); >>

Thanks for reading! I hope you found this post useful!

Источник

Java jframe exit on close

An extended version of java.awt.Frame that adds support for the JFC/Swing component architecture. You can find task-oriented documentation about using JFrame in The Java Tutorial, in the section How to Make Frames. The JFrame class is slightly incompatible with Frame . Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame . This is different from the AWT Frame case. As a convenience, the add , remove , and setLayout methods of this class are overridden, so that they delegate calls to the corresponding methods of the ContentPane . For example, you can add a child component to a frame as follows:

Nested Class Summary

Nested classes/interfaces inherited from class java.awt.Frame

Nested classes/interfaces inherited from class java.awt.Window

Nested classes/interfaces inherited from class java.awt.Container

Nested classes/interfaces inherited from class java.awt.Component

Field Summary

The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane .

Fields inherited from class java.awt.Frame

Fields inherited from class java.awt.Component

Fields inherited from interface javax.swing.WindowConstants

Fields inherited from interface java.awt.image.ImageObserver

Constructor Summary

Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.

Method Summary

All Methods Static Methods Instance Methods Concrete Methods
Modifier and Type Method and Description
protected void addImpl (Component comp, Object constraints, int index)

Returns true if newly created JFrame s should have their Window decorations provided by the current look and feel.

Provides a hint as to whether or not newly created JFrame s should have their Window decorations (such as borders, widgets to close the window, title. ) provided by the current look and feel.

Sets the transferHandler property, which is a mechanism to support transfer of data into this component.

Methods inherited from class java.awt.Frame

Methods inherited from class java.awt.Window

Methods inherited from class java.awt.Container

Methods inherited from class java.awt.Component

Methods inherited from class java.lang.Object

Methods inherited from interface java.awt.MenuContainer

Field Detail

EXIT_ON_CLOSE

public static final int EXIT_ON_CLOSE

The exit application default window close operation. If a window has this set as the close operation and is closed in an applet, a SecurityException may be thrown. It is recommended you only use this in an application.

rootPane

The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane .

rootPaneCheckingEnabled

protected boolean rootPaneCheckingEnabled

If true then calls to add and setLayout will be forwarded to the contentPane . This is initially false, but is set to true when the JFrame is constructed.

accessibleContext

Constructor Detail

JFrame

Constructs a new frame that is initially invisible. This constructor sets the component’s locale property to the value returned by JComponent.getDefaultLocale .

JFrame

Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title. This constructor sets the component’s locale property to the value returned by JComponent.getDefaultLocale .

JFrame

public JFrame(String title) throws HeadlessException

Creates a new, initially invisible Frame with the specified title. This constructor sets the component’s locale property to the value returned by JComponent.getDefaultLocale .

JFrame

public JFrame(String title, GraphicsConfiguration gc)

Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device. This constructor sets the component’s locale property to the value returned by JComponent.getDefaultLocale .

Method Detail

frameInit

createRootPane

processWindowEvent

Processes window events occurring on this component. Hides the window or disposes of it, as specified by the setting of the defaultCloseOperation property.

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.

getDefaultCloseOperation

public int getDefaultCloseOperation()

setTransferHandler

Sets the transferHandler property, which is a mechanism to support transfer of data into this component. Use null if the component does not support data transfer operations. If the system property suppressSwingDropSupport is false (the default) and the current drop target on this component is either null or not a user-set drop target, this method will change the drop target as follows: If newHandler is null it will clear the drop target. If not null it will install a new DropTarget . Note: When used with JFrame , TransferHandler only provides data import capability, as the data export related methods are currently typed to JComponent . Please see How to Use Drag and Drop and Data Transfer, a section in The Java Tutorial, for more information.

getTransferHandler

update

Just calls paint(g) . This method was overridden to prevent an unnecessary call to clear the background.

setJMenuBar

getJMenuBar

isRootPaneCheckingEnabled

protected boolean isRootPaneCheckingEnabled()

setRootPaneCheckingEnabled

protected void setRootPaneCheckingEnabled(boolean enabled)

addImpl

protected void addImpl(Component comp, Object constraints, int index)

Adds the specified child Component . This method is overridden to conditionally forward calls to the contentPane . By default, children are added to the contentPane instead of the frame, refer to RootPaneContainer for details.

remove

Removes the specified component from the container. If comp is not the rootPane , this will forward the call to the contentPane . This will do nothing if comp is not a child of the JFrame or contentPane .

setLayout

Sets the LayoutManager . Overridden to conditionally forward the call to the contentPane . Refer to RootPaneContainer for more information.

getRootPane

setRootPane

setIconImage

Sets the image to be displayed as the icon for this window. This method can be used instead of setIconImages() to specify a single image as a window’s icon. The following statement:

ArrayList imageList = new ArrayList(); imageList.add(image); setIconImages(imageList);

Note : Native windowing systems may use different images of differing dimensions to represent a window, depending on the context (e.g. window decoration, window list, taskbar, etc.). They could also use just a single image for all contexts or no image at all.

getContentPane

setContentPane

Sets the contentPane property. This method is called by the constructor. Swing’s painting architecture requires an opaque JComponent in the containment hierarchy. This is typically provided by the content pane. If you replace the content pane it is recommended you replace it with an opaque JComponent .

getLayeredPane

setLayeredPane

getGlassPane

setGlassPane

getGraphics

Creates a graphics context for this component. This method will return null if this component is currently not displayable.

repaint

public void repaint(long time, int x, int y, int width, int height)

Repaints the specified rectangle of this component within time milliseconds. Refer to RepaintManager for details on how the repaint is handled.

setDefaultLookAndFeelDecorated

public static void setDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated)

Provides a hint as to whether or not newly created JFrame s should have their Window decorations (such as borders, widgets to close the window, title. ) provided by the current look and feel. If defaultLookAndFeelDecorated is true, the current LookAndFeel supports providing window decorations, and the current window manager supports undecorated windows, then newly created JFrame s will have their Window decorations provided by the current LookAndFeel . Otherwise, newly created JFrame s will have their Window decorations provided by the current window manager. You can get the same effect on a single JFrame by doing the following:

JFrame frame = new JFrame(); frame.setUndecorated(true); frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);

isDefaultLookAndFeelDecorated

public static boolean isDefaultLookAndFeelDecorated()

Returns true if newly created JFrame s should have their Window decorations provided by the current look and feel. This is only a hint, as certain look and feels may not support this feature.

paramString

Returns a string representation of this JFrame . This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null .

getAccessibleContext

Gets the AccessibleContext associated with this JFrame. For JFrames, the AccessibleContext takes the form of an AccessibleJFrame. A new AccessibleJFrame instance is created if necessary.

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

Оцените статью