Java swing close windows

How do I handle a window closing event in Swing?

Here you will see how to handle the window closing event of a JFrame . What you need to do is to implement a java.awt.event.WindowListener interface and call the frame addWindowListener() method to add the listener to the frame instance. To handle the closing event implements the windowClosing() method of the interface.

Instead of implementing the java.awt.event.WindowListener interface which require us to implement the entire methods defined in the interface, we can create an instance of WindowAdapter object and override only the method we need, which is the windowsClosing() method. Let’s see the code snippet below.

package org.kodejava.swing; import javax.swing.JFrame; import java.awt.Button; import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class WindowClosingDemo extends JFrame < public static void main(String[] args) < WindowClosingDemo frame = new WindowClosingDemo(); frame.setSize(new Dimension(500, 500)); frame.add(new Button("Hello World")); // Add window listener by implementing WindowAdapter class to // the frame instance. To handle the close event we just need // to implement the windowClosing() method. frame.addWindowListener(new WindowAdapter() < @Override public void windowClosing(WindowEvent e) < System.out.println("WindowClosingDemo.windowClosing"); System.exit(0); >>); // Show the frame frame.setVisible(true); > > 

A programmer, recreational runner and diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕ every little bit helps, thank you 🙏

Читайте также:  Php include error page

Источник

How to Close a Window in Java

wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, 10 people, some anonymous, worked to edit and improve it over time.

This article has been viewed 143,260 times.

This article will show you how to close a window in Java. Closing a window is much easier using Swing’s JFrame , but it’s also doable using AWT’s Frame .

Using javax.swing.JFrame

Image titled Close window java step1.png

Image titled Close window java step2_with_import.png

  • WindowConstants.EXIT_ON_CLOSE — Closes the frame and terminates the execution of the program.
  • WindowConstants.DISPOSE_ON_CLOSE — Closes the frame and does not necessarily terminate the execution of the program.
  • WindowConstants.HIDE_ON_CLOSE — Makes the frame appear like it closed by setting its visibility property to false. The difference between HIDE_ON_CLOSE and DISPOSE_ON_CLOSE is that the latter releases all of the resources used by the frame and its components.
  • WindowConstants.DO_NOTHING_ON_CLOSE — Does nothing when the close button is pressed. Useful if you wish to, for example, display a confirmation dialog before the window is closed. You can do that by adding a WindowListener to the frame and overriding windowClosing method. Example of the custom close operation:
    frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowAdapter()  @Override public void windowClosing(WindowEvent e)  // Ask for confirmation before terminating the program. int option = JOptionPane.showConfirmDialog( frame, "Are you sure you want to close the application?", "Close Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (option == JOptionPane.YES_OPTION)  System.exit(0); > > >); 

    Using java.awt.Frame

    Image titled Close window java step1 method2.png

    Image titled Close window java step2 method2.png

    Add window listener. Call addWindowListener method on the instance. The required argument is WindowListener . You can either implement every method of the WindowListener interface or override only the methods you need from WindowAdapter class.

    Image titled Close window java step3 method2.png

      Dispose the window after the close button is clicked:
        Call dispose method inside windowClosing method.
      frame.addWindowListener(new WindowAdapter()  @Override public void windowClosing(WindowEvent e)  // Dispose the window after the close button is clicked. dispose(); > >); 
      frame.addWindowListener(new WindowAdapter()  @Override public void windowClosing(WindowEvent e)  // Terminate the program after the close button is clicked. System.exit(0); > >); 

      Expert Q&A

      Using WindowAdapter you don’t have to implement each and every method WindowListener contract tells us to, but only the ones we need.

      You Might Also Like

      Check Null in Java

      Create a New Java Project in Eclipse

      Set Java Home

      How to Set JAVA_HOME for JDK & JRE: A Step-by-Step Guide

      Check Your Java Version in the Windows Command Line

      Use Easy Windows CMD Commands to Check Your Java Version

      Do Division in Java

      How to Do Division in Java (Integer and Floating Point)

      Compile & Run Java Program Using Command Prompt

      Compile and Run Java Program by Notepad

      How to Compile and Run Java Programs Using Notepad++

      Источник

      How to Close Java Program or Swing Application with Example

      In order to close the Java program, we need to consider which kind of Java application it is?, because termination of Java application varies between normal core java programs to swing GUI applications. In general, all Java program terminates automatically once all user threads created by program finishes its execution, including main thread. JVM doesn’t wait for the daemon thread so as soon as the last user thread is finished, the Java program will terminate. If you want to close or terminate your java application before this your only option is to use System.exit(int status) or Runtime.getRuntime().exit().

      This causes JVM to abandon all threads and exit immediately. Shutdown hooks are get called to allow some last-minute clearing before JVM actually terminates. System.exit() also accept an int status parameter where a non-zero value denotes abnormal execution and its result returned by java command to the caller.

      In this java tutorial, we will see an example of closing both the Java program and the Java Swing application. This is also a good swing interview question that you can ask any GUI developer and my second article in the swing after writing invokeAndWait vs invokeLater

      1. Example of Closing Java program using System.exit()

      Here is a code example of closing the Java program by calling System.exit() method. Remember non zero arguments to exit() method like exit(1) denotes abnormal termination of Java application.

      import java.util.logging.Level ;
      import java.util.logging.Logger ;

      /**
      *Java program which terminates itself by using System.exit() method , non zero call to exit() method denotes abnormal termination.
      */

      public class JavaCloseExample

      public static void main ( String args []) throws InterruptedException

      Thread t = new Thread () <
      @Override
      public void run () <
      while ( true ) <
      System. out . println ( «User thread is running» ) ;
      try <
      Thread. sleep ( 100 ) ;
      > catch ( InterruptedException ex ) <
      Logger. getLogger ( JavaCloseExample. class . getName ()) . log ( Level. SEVERE , null , ex ) ;
      >
      >
      >
      > ;

      t. start () ;
      Thread. sleep ( 200 ) ;
      System. out . println ( «terminating or closing java program» ) ;
      System. exit ( 1 ) ; //non zero value to exit says abnormal termination of JVM
      >
      >

      Output:
      User thread is running
      User thread is running
      terminating or closing java program
      Java Result: 1 //1 is what we passed to exit() method

      This Java program first creates a Thread in the main method and start it which prints “ User thread is running ” and then main thread sleep for 200 Millisecond, till then other user thread is running and printing but once main thread woken up it terminates the program by calling exit() method of java.lang . System class.

      2. How to close Java swing application from the program

      Swing application mostly uses JFrame as a top-level container which provides two options to close swing GUI application from code. The first option which is the default is EXIT_ON_CLOSE which terminates the Java swing GUI program when you click the close button on the JFrame window.

      Another option is DISPOSE_ON_CLOSE which terminates JVM if the last displayable window is disposed of. Difference between EXIT_ON_CLOSE and DISPOSE_ON_CLOSE is that if you have a non-daemon thread running it will not be closed in case of DISPOSE_ON_CLOSE , while EXIT_ON_CLOSE terminate JVM even if user thread is running.

      Run the below example by uncommenting DISPOSE_ON_CLOSE in your IDE and you can see user thread running even after clicking on the close button. here is a complete code example of closing the Swing application in Java.

      import java.util.logging.Level ;
      import java.util.logging.Logger ;
      import javax.swing.JFrame ;

      /**
      * Java swing program which terminates itself by calling EXIT_ON_CLOSE and DISPOSE_ON_CLOSE
      */

      public class CloseSwingExample

      public static void main ( String args []) throws InterruptedException

      JFrame frame = new JFrame ( «Sample» ) ;
      //frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); won’t terminate JVM if user thread running
      frame. setDefaultCloseOperation ( JFrame. EXIT_ON_CLOSE ) ;
      frame. setSize ( 200 , 200 ) ;
      frame. setVisible ( true ) ;

      Thread t = new Thread ()

      @Override
      public void run () <
      while ( true ) <
      System. out . println ( «User thread is running» ) ;
      try <
      Thread. sleep ( 100 ) ;
      > catch ( InterruptedException ex ) <
      Logger. getLogger ( CloseSwingExample. class . getName ()) . log ( Level. SEVERE , null , ex ) ;
      >
      >
      >
      > ;

      Источник

      Properly closing Swing windows

      There are many subjects one has to know when working with Swing and one of them is window closing. A beginner pass through some steps (and yes, I consider myself a beginner in Swing) and here are those I experienced myself.

      Hiding is default

      In the first step, you realize that by clicking the cross in the title bar, the window only disappears. It’s not disposed of, and if it’s your main application’s window, that’s bad because it means you’ve lost any handle on the underlying running JVM. It means users just keep spawning new JVMs when launching the application and do not close them, using more and more of the platform memory.

      The basics

      By then, you learn that any Swing JFrame can be set the right close operation by calling its setDefaultCloseOperation() method. This let you choose the behavior when closing the window: for example, WindowConstants.EXIT_ON_CLOSE exits the JVM when closing the window. This should be set of course on your main window.

      Shutdown hook

      This method has a slight disadvantage, however. What if we need to do some cleaning operations before exiting the JVM? There’s something called shutdown hooks that the JVM calls just before exiting. It already is explained in this post and fits our needs…​ provided what we need to do is related to the entire application.

      Window listeners

      But how can we release resources that are needed by a popup window before the JVM exits? The last way I found was to use window listeners: by implementing WindowListener (or better, by extending WindowAdapter ), one can code the desired behavior easily in the windowClosed() method.

      Nicolas Fränkel

      Nicolas Fränkel

      Developer Advocate with 15+ years experience consulting for many different customers, in a wide range of contexts (such as telecoms, banking, insurances, large retail and public sector). Usually working on Java/Java EE and Spring technologies, but with focused interests like Rich Internet Applications, Testing, CI/CD and DevOps. Also double as a trainer and triples as a book author.

      Swing

      Strategies to improve your knowledge

      If you’ve got a professional attitude regarding your developer career, chances are you’re looking to improve your knowledge, whether it’s language-related or framework-related (or even process-related but it is more far-fetched). So far, I found the following ways to do so, each step bringing deeper knowledge than the former: The first strategy when you want to learn about something is to read about it. This is the easiest, since there are so many resources available online. Th

      Nicolas Fränkel

      Managing unmanaged beans in CDI

      During these (much deserved) vacations, I worked on a pet project of mine which uses CDI with the Weld implementation and SLF4J with the Logback implementation. The terms of the problem were very simple: Iwanted the logs of my application to be displayed in a Swing table, i.e. a Logback appender had to write in a table. The table was managed in CDI but the appender was not: this was no surprise since many older-generation frameworks have a lifecycle management on their own. Prior-to-JEE6 Servl

      Nicolas Fränkel

      Источник

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