Java jframe как закрыть

JFrame – сворачиваем, разворачиваем и закрываем

Как каждое нормальное окно, JFrame имеет кнопки для управления размерами окна, а также для его закрытия. Эти кнопки располагаются в правом верхнем углу заголовка окна JFrame. Здесь есть кнопка минимизации окна, при нажатии на которую окно сворачивается. Имеется кнопка максимизации размеров окна, когда JFrame разворачивается на весь экран. Как только окно развернуто, появляется кнопка возврата к «нормальному» размеру окна до разворачивания. Ну и последняя кнопка – это закрытие окна. Интересно то, что для выполнения этих задач разработчик может использовать специальные методы JFrame. Рассмотрим, как можно сворачивать, разворачивать и закрывать окно, используя эти методы.

Для того, чтобы свернуть окно, используется метод setState с параметром JFrame.ICONIFIED. Чтобы развернуть окно на весь дисплей вызывается метод setExtendedState с параметром JFrame.MAXIMIZED_BOTH. Для восстановления нормального размера после того, как окно было развернуто, вызываем всё тот же setExtendedState, но только с параметром JFrame.NORMAL. Далее в случае, если потребуется скрыть окно, используем setVisible с параметром false. Если окно, которое мы хотим скрыть, является главным окном приложения, то при скрытии окна потребуется осуществить выход из приложения. Например, у нас есть пункт главного меню «Выход», при выборе которого нужно выйти из приложения, то тогда можно сразу вызвать System.exit(0).

Ну и для демонстрации вышеописанных методов предлагаю код приложения, внешний вид которого представлен на рисунке.

jframe_resizing

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

Читайте также:  Debug class files in java

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
>

public static void main(String[] args) javax.swing.SwingUtilities.invokeLater(new Runnable() public void run() createGUI();
>
>);
>
>

Источник

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.

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!

Источник

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.

Источник

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