- Setting the Behavior When Closing a JFrame
- JFrame.defaultCloseOperation(int option)
- java.awt.Window.addWindowListener(java.awt.event.WindowListener l)
- java.awt.Window.processWindowEvent(java.awt.event.WindowEvent e)
- Java swing close one frame
- How to Exit JFrame on Close in Java Swing
- Exit JFrame on Close in Java Swing
- Creating a Java JFrame
- Two Approaches on Closing JFrame
- JFrame – сворачиваем, разворачиваем и закрываем
Setting the Behavior When Closing a JFrame
There are a number of techniques that one can use to close a frame in Java. Each has its advantages and disadvantages. Three techniques are presented below in general decreasing preference order:
JFrame.defaultCloseOperation(int option)
This is the simplest technique. All you need to do is to call the defaultClostOperation method of a JFrame , supplying the desired option value.
The possibilities for the option value are:
- JFrame.EXIT_ON_CLOSE — A System.exit(0) call will be executed, exiting the entire application.
- Do NOT use this option if the program is running as an applet as this will cause the browser to crash!
The advantage of the technique is that it is very simple and easy, but it does not allow much flexibility to do any custom operations during the frame closing.
public class MyFrame extends JFrame public MyFrame() < setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); >. >
For dynamically configurable frame closing behavior, supply the option value to the constructor of the frame. This would be done by the controller, which would instantiate the frame with either an EXIT_ON_CLOSE option if it was an application or a DO_NOTHING_ON_CLOSE or DISPOSE_ON_CLOSE if it were an applet.
java.awt.Window.addWindowListener(java.awt.event.WindowListener l)
(Note that javax.swing.JFrame is a subclass of java.awt.Window and thus inherits this method.)
In this technique a WindowListener interface implentation is added to the frame, where the listener has a method, windowClosing() , that is called when the frame is closed.
In practice, on overrides the windowClosing() method of WindowAdapter , a no-op implementation of WindowListener . This way, one doesn’t have to worry about all the other methods of the WindowListener .
public class MyFrame extends JFrame public MyFrame() < addWindowListener(new java.awt.event.WindowAdapter() < public void windowClosing(java.awt.event.WindowEvent e) < System.exit(0); >>); > . >
This technique has the advantage that any sort of custom processing can be done when the frame is closed. The frame can be constructed with a command that the windowClosing method calls or with an complete WindowListener object, thus enabling dynamic configuration of the frame closing behavior. This is very useful when you want to run the same frame as either a regular application or as an applet — the controller will instantiate the frame with the proper closing behavior.
The disadvantage of this technique is the larger code required than the first technique for standard window closing behaviors.
java.awt.Window.processWindowEvent(java.awt.event.WindowEvent e)
(Note that javax.swing.JFrame is a subclass of java.awt.Window and thus inherits this method.)
In this technique, the processWindowEvent method, which is called when the frame is closed, is overriden to provide the desired behavior. The supplied WindowEvent parameter is tested to see if it is the event for the window is being closed and if so, the desired behavior is executed.
public class MyFrame extends JFrame public MyFrame() < protected void processWindowEvent(WindowEvent e) < super.processWindowEvent(e); if(e.getID() == WindowEvent.WINDOW_CLOSING) < System.exit(0); >> > . >
For dynamic behavior, a command supplied to the constructor of the frame can be run when the WINDOW_CLOSING event is detected.
The advantage of this technique is that an entire object to handle the frame closing needs to be constructed but at the expense of a more complicated logical process.
Java swing close one frame
Java Swing Tutorials — Herong’s Tutorial Examples — v4.31, by Herong Yang
∟ Closing Frame and Terminating Application
This section provides 3 solutions and sample programs on how to close the main frame and terminate the application.
Problem: I have a frame window displayed on the screen and I want to close the frame and terminate the application, when user invokes the close command from the window’s system menu, or clicks on the close icon from the window’s system icon list.
Solution 1: You can use the JFrame.setDefaultCloseOperation() method to change the default behavior option of JFrame responding to the window closing event. Select the EXIT_ON_CLOSE option will terminate the application immediately. Of course, when the application is terminated, all frames will be closed automatically. The following sample code, JFrameClose1.java, shows you how to do this.
/* JFrameClose1.java * Copyright (c) 1997-2018 HerongYang.com. All Rights Reserved. */ import javax.swing.*; public class JFrameClose1 < public static void main(String[] a) < JFrame f = new JFrame(); f.setTitle("Closing Frame with Default Close Operation"); f.setBounds(100,50,500,300); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); >>
Solution 2: You can extend JFrame class to have your own frame class, so that you can override the default processWindowEvent() method to terminate the application. Of course, calling System.exit(0) is the quickest way to terminate an application. The following sample code, JFrameClose2.java, shows you how to do this.
/* JFrameClose2.java * Copyright (c) 1997-2018 HerongYang.com. All Rights Reserved. */ import java.awt.event.*; import javax.swing.*; public class JFrameClose2 < public static void main(String[] a) < MyJFrame f = new MyJFrame(); f.setTitle("Closing Frame with Process Window Event"); f.setBounds(100,50,500,300); f.setVisible(true); >static class MyJFrame extends JFrame < protected void processWindowEvent(WindowEvent e) < if (e.getID() == WindowEvent.WINDOW_CLOSING) < System.exit(0); >> > >
Solution 3: You can create a new window event listener class and add an object of this listener class to the JFrame object. In the new window event listener, you can implement your owner version of windowClosing() handler method. Of course, the quickest way to create a new window event listener class is to extend the WindowAdapter class. The following sample code, JFrameClose3.java, shows you how to do this.
/* JFrameClose3.java * Copyright (c) 1997-2018 HerongYang.com. All Rights Reserved. */ import java.awt.event.*; import javax.swing.*; public class JFrameClose3 < public static void main(String[] a) < JFrame f = new JFrame(); f.setTitle("Closing Frame with Window Listener"); f.setBounds(100,50,500,300); f.addWindowListener(new MyWindowListener()); f.setVisible(true); >static class MyWindowListener extends WindowAdapter < public void windowClosing(WindowEvent e) < System.exit(0); >> >
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.
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.
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!
JFrame – сворачиваем, разворачиваем и закрываем
Как каждое нормальное окно, JFrame имеет кнопки для управления размерами окна, а также для его закрытия. Эти кнопки располагаются в правом верхнем углу заголовка окна JFrame. Здесь есть кнопка минимизации окна, при нажатии на которую окно сворачивается. Имеется кнопка максимизации размеров окна, когда JFrame разворачивается на весь экран. Как только окно развернуто, появляется кнопка возврата к «нормальному» размеру окна до разворачивания. Ну и последняя кнопка – это закрытие окна. Интересно то, что для выполнения этих задач разработчик может использовать специальные методы JFrame. Рассмотрим, как можно сворачивать, разворачивать и закрывать окно, используя эти методы.
Для того, чтобы свернуть окно, используется метод setState с параметром JFrame.ICONIFIED. Чтобы развернуть окно на весь дисплей вызывается метод setExtendedState с параметром JFrame.MAXIMIZED_BOTH. Для восстановления нормального размера после того, как окно было развернуто, вызываем всё тот же setExtendedState, но только с параметром JFrame.NORMAL. Далее в случае, если потребуется скрыть окно, используем setVisible с параметром false. Если окно, которое мы хотим скрыть, является главным окном приложения, то при скрытии окна потребуется осуществить выход из приложения. Например, у нас есть пункт главного меню «Выход», при выборе которого нужно выйти из приложения, то тогда можно сразу вызвать System.exit(0).
Ну и для демонстрации вышеописанных методов предлагаю код приложения, внешний вид которого представлен на рисунке.
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;public static void createGUI() JFrame.setDefaultLookAndFeelDecorated(true);
final JFrame frame = new JFrame(«Test frame»);JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());JButton minButton = new JButton(«Minimize»);
minButton.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) frame.setState(JFrame.ICONIFIED);
>
>);
panel.add(minButton);JButton maxButton = new JButton(«Maximize»);
maxButton.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
>
>);
panel.add(maxButton);JButton normalButton = new JButton(«Normal»);
normalButton.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) frame.setExtendedState(JFrame.NORMAL);
>
>);
panel.add(normalButton);JButton exitButton = new JButton(«Exit»);
exitButton.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) frame.setVisible(false);
System.exit(0);
>
>);
panel.add(exitButton);frame.getContentPane().add(panel);
frame.setPreferredSize(new Dimension(400, 80));frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
>public static void main(String[] args) javax.swing.SwingUtilities.invokeLater(new Runnable() public void run() createGUI();
>
>);
>
>