Close window in java swing

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.

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.

Читайте также:  Zoom style in css

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!

Источник

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 ) ;
>
>
>
> ;

Источник

JFrame close example: How to close your JFrame when the user presses the close icon

By default, when you create a JFrame in a Java client-side application, and the user presses the exit button on the JFrame, the JFrame window is closed, but the application continues to run, essentially running in the background, as you typically don’t have a way of showing that JFrame again.

Of course what you really want to do is prompt the user with some type of «You’re about to quit the application — are you sure?» dialog, or just quit the application if you don’t want to be that nice. In this article we’ll demonstrate how to close the frame, and your application, when your application receives a «close window» (close frame) event. There are several ways to do this, and I’ll show each of them in this article.

1) Handling the window closing event with a WindowListener class

There are several ways to accomplish this. The first way is to add a WindowListener to your JFrame. Step 1 in this process is to create your WindowListener . I’ll show my WindowListener code here as a separate class, but you can also create this as an anonymous inner class if you prefer:

class MyWindowListener implements WindowListener < public void windowClosing(WindowEvent arg0) < System.exit(0); >public void windowOpened(WindowEvent arg0) <> public void windowClosed(WindowEvent arg0) <> public void windowIconified(WindowEvent arg0) <> public void windowDeiconified(WindowEvent arg0) <> public void windowActivated(WindowEvent arg0) <> public void windowDeactivated(WindowEvent arg0) <> >

As you can see from this code, there is a lot of «do nothing» code in this window listener code (boilerplate methods that provide no functionality), with one method ( windowClosing ) that actually does what you want — it calls System.exit() when the «window closing» event is fired. Note that all of the «do nothing» methods I refer to are required to fulfill the requirements of the WindowListener interface.

After creating this class all you need to do is find a reference to your JFrame, and add a reference to an instance of your WindowListener, like this:

myJFrame.addWindowListener(new MyWindowListener());

This can be nice when you want to override several of these event methods, but is overkill if you just want to handle this one event.

2) Handling the window closing event with a WindowAdapter

If you don’t want to see the overhead of all those do-nothing methods you can use a WindowAdapter instead of implementing the WindowListener interface yourself. The WindowAdapter implements the WindowListener interface, so you don’t have to. It’s intended for making code like this a lot simpler. You just need to create an instance of a WindowAdapter and override the windowClosing method, like this:

myJFrame.addWindowListener(new WindowAdapter() < public void windowClosing(WindowEvent we) < System.exit(0); >>);

As you can see, this is a lot less code than the previous example. While creating your own class to implement the WindowListener interface is handy when you need to override several methods in that interface, the adapter is nice for situations like this, where you’re implementing only one method.

3) A simple way to handle the window closing event

Now, if you want a really fast way of handling this you can just tell your JFrame how to handle this event with a default operation. You do this with a simple method call on your JFrame object, like this:

myJFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

Of course that is a lot simpler, and it’s very useful when you’re creating prototypes, but you probably don’t want to do this in production applications. You’ll usually want to warn the user before shutting down the entire application.

Источник

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