Java jframe on exit event

JFrame basic tutorial and examples

In the code above we create a frame window entitled “Demo program for JFrame”.

2. Setting layout manager

frame.setLayout(new GridBagLayout());
frame.setLayout(new GridLayout());
frame.setLayout(new CardLayout());
frame.setLayout(new FlowLayout());

NOTE: the call setLayout(layout) is equivalent to this call:

frame.getContentPane().setLayout(layout);

3. Adding child components to JFrame

  • We can use the method add(Component) to add a component to the frame’s content pane. For example, adding a text field:
JTextField textFieldUserName = new JTextField(50); frame.add(textFieldUserName);
frame.getContentPane().add(Component);
add(textFieldUserName, BorderLayout.CENTER);
GridBagConstraints constraint = new GridBagConstraints(); constraint.gridx = 1; constraint.gridy = 0; // set other constraints. JTextField textFieldUserName = new JTextField(20); add(textFieldUserName, constraint);

The method setJMenuBar(JMenuBar) is used to add a menu bar to the frame. The following example code adds a menu bar with a File > Exit menu:

JMenuBar menuBar = new JMenuBar(); JMenu menuFile = new JMenu("File"); JMenuItem menuItemExit = new JMenuItem("Exit"); menuFile.add(menuItemExit); menuBar.add(menuFile); // adds menu bar to the frame frame.setJMenuBar(menuBar);

4. Specifying window closing behavior for JFrame

We can specify which action will be executed when the user clicks on the frame’s close button:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

5. Showing JFrame on screen

frame.setSize(300, 200); frame.setVisible(true);

empty jframe window

Image:

It is recommended to instantiate and showing the frame in the Swing event dispatcher thread (EDT) like this:

SwingUtilities.invokeLater(new Runnable() < @Override public void run() < new SwingJFrameDemo().setVisible(true); >>);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setLocation(new java.awt.Point(100, 100));
frame.setBounds(100, 100, 300, 400);
frame.setBounds(new java.awt.Rectangle(100, 100, 300, 400));

6. Handling window events for JFrame

The interface java.awt.event.WindowListener defines various window events to which we can listen if interested. The method addWindowListener(WindowListener) of JFrame class is used to add a window listener for the frame.

    Listen to window events by implementing the WindowListener interface: In this way, have the frame class implements the WindowListener interface and overrides all its methods, like the following example:

public class FrameDemo extends JFrame implements WindowListener < public FrameDemo() < super("Frame Demo"); // initialization code. setSize(300, 400); addWindowListener(this); setVisible(true); >public void windowActivated(WindowEvent event) < System.out.println("The window has been activated"); >public void windowClosed(WindowEvent event) < System.out.println("The window has been closed"); >public void windowClosing(WindowEvent event) < System.out.println("About to close the window"); >public void windowDeactivated(WindowEvent event) < System.out.println("The window has been deactivated"); >public void windowDeiconified(WindowEvent event) < System.out.println("The window has been restored"); >public void windowIconified(WindowEvent event) < System.out.println("The window has been minimized"); >public void windowOpened(WindowEvent event) < System.out.println("The window has been opened"); >>

In case we want to listen to only one (or more, but not all) events, we can create a listener class that extends from the WindowAdapter class and override only the interested event methods:

class MyWindowListener extends WindowAdapter < // overrides only one method: public void windowClosing(WindowEvent event) < System.out.println("About to close the window"); >>

Then add this listener for the frame as follows:

MyWindowListener listener = new MyWindowListener(); frame.addWindowListener(listener);

Or we can use anonymous class syntax like this:

addWindowListener(new WindowAdapter() < public void windowClosing(WindowEvent event) < System.out.println("About to close the window"); >>);

7. Customizing JFrame’s appearance

Image icon = new javax.swing.ImageIcon("images/android.png").getImage(); frame.setIconImage(icon);

Here the image android.png is placed under directory images which is relative to the application’s directory.
Image:

Читайте также:  Внешняя таблица стилей

The icon image is in the classpath or in jar files:

String iconPath = "/net/codejava/swing/jframe/android.png"; Image icon = new ImageIcon(getClass().getResource(iconPath)).getImage(); frame.setIconImage(icon);
frame.getContentPane().setBackground(Color.GREEN);

If the frame is undecorated, its border, title bar and window buttons are all removed, only keep its content pane visible.

8. JFrame demo program

To demonstrate the techniques mentioned in this article and for your reference, we create a Swing program looks like the following:

jframe demo program

On clicking the close button, a confirm message dialog appears:

confirm message dialog

If “Yes” is selected, the program exits, otherwise the frame remains visible on screen.

You can download this demo program’s source code and executable jar file in the attachments section.

Other Java Swing Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

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.

Читайте также:  Inline line height in html

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.

Источник

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 🙏

Источник

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.

Читайте также:  Application made with python

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.

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!

Источник

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