Java close this window

How to close the JFrame window programmatically in Java

In this tutorial, we will learn the various methods and techniques by which a JFrame window can be closed programmatically in Java.

There are many ways by which we can close the JFrame window programmatically in Java. But yes closing a JFrame is difficult to get into the head because there are a lot of variants on how we can do it.

Some of the primary ways can be :

  • Make the JFrame window invisible and keep it ready to be made visible again
  • Make the JFrame Window invisible and store it in a cold storage
  • We can also close the window by clicking on the cross button X. While clicking the X button at the top right corner, the JFrame window programmatically is sent to the window closing event.

So we discussed some basic ideas about how to close the JFrame window in Java. Let’s categorize them in a proper fashion:

  • Final Close: When you want to get rid of the JFrame window and never want to use it again then call the dispose() function immediately after the setVisible ( false ) is called. This is done to avoid memory leaks since Java GUI is not so smart enough to do its own garbage collection
Читайте также:  Php check if string contains substring

  • Temporary Close: When you want to close the window for a short period of time then you can call the setVisible (false) function to make the window invisible and to bring it back call setVisible to true.
  • ShortHand WindowClosingEvent handler: There are in total 3 shortcuts to execute the closing operation of a JFrame Window.

(1) If the programmer wants to dispose of the window then he/she can write this code instead to invoke the window closing event handler.

this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)

(2) If the programmer wants to hide the window temporarily, then he/she can write this code instead to invoke the window closing event handler

this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)

(3) If the programmer wants to permanently close the window call this code.

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

Hope this information will help you all a lot in learning JFrame and Java swing.

Источник

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,298 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 and Run Java Program by Notepad

      How to Compile and Run Java Programs Using Notepad++

      Источник

      Disposing and closing windows in Java

      To determine when a Window is closing in Java, use the WindowListener, which is the listener interface for receiving window events.. Above, we have used the windowClosing() method, which is invoked when a window is in the process of being closed − The following is an example to determine when a Frame or Window is closing in Java − Example So some suggestions: The Window Closing event should be handled from the Frame itself.

      Disposing and closing windows in Java

      You can get a reference to the frame, from the source property of the event:

      class MyWindowListener extends WindowAdapter < public void windowClosing(WindowEvent e)< Frame frame = (Frame) e.getSource(); frame.dispose(); >> 

      Alternatively, since this is an anonymous class (presumably) declared within the constructor, you also have access to the enclosing instance, so you can also write it as:

      class MyFrameClass extends Frame < public MyFrameClass() < this.addWindowListener(new WindowAdapter()< public void windowClosing(WindowEvent e)< MyFrameClass.this.dispose(); >>); > > 

      Or you can make it simpler still (as your WindowListener does not have a method of its own called «dispose»):

      public void windowClosing(WindowEvent e)

      Not a stupid question. Because of the garbage collector its not such a big issue, however, there are some times when you will want to execute some cleanup when a window closes. So some suggestions:

      The Window Closing event should be handled from the Frame itself. For instance:

       this.addWindowListener(new WindowAdapter() < public void windowClosing(WindowEvent e)< //code here to perform as the window is about to close. >>); 

      And I would suggest that you create a separate class for your main method that will invoke the Frame etc.

      This is used to close Jframe with an event handler. current Jframe public class LoginForm extends JFrame < LoginForm() < //Some code for Jframe and its components. if(Condition) disposewindow(); >private void disposewindow() < WindowEvent closingEvent = new WindowEvent(LoginForm.this, WindowEvent.WINDOW_CLOSING); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(closingEvent); >//you can can use for alternate of dispose()event and it post some event handler **Closing event** , // if we can use this closing event to open new window with conditions. //It means closing child window with closing event, get this flag in main window to make main window as Disable or Enable state 

      //In parent window @Override

       public void windowClosing(WindowEvent arg0) < // TODO Auto-generated method stub this.frame.disable(); >

      How to detect when a specific window is closed in java, 1 Answer. Sorted by: 3. Because both frameA and frameB are using the same instance of WindowListener (this), when either frame is closed, your …

      Java swing close window without exiting app

      You can use either Frame.hide() or Frame.dispose(). I would also recommend to look into JDialog or JOptionPane

      Correction: hide() is deprecated. SetVisible(false) should be used instead

      Maybe a cleaner way is just change the setDefaultCloseOperation from EXIT_ON_CLOSE to DISPOSE_ON_CLOSE :

      setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 

      You can call setVisible(false) on the frame.

      You might also want to call setDefaultCloseOperation on the frame passing in HIDE_ON_CLOSE (info here: http://java.sun.com/javase/6/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation%28int%29). That will prevent the app from going away if they user hits the «X» on the JFrame to close it.

      How to close a external application with java, 2 Answers. You can do this by executing a process to close the process that you want to close. In your comments I can see taskkill, which …

      How to find and close running Win-Process which is Java app from within other Java app?

      wmic process where caption="java.exe" get commandline,description,processid 

      to get the list of processes and their associated command line like in your screenshot. Then you get the ID of the command you want to kill and kill it with taskkill /pid xxx .

      Closing on a single window closes all the frames in java, If you want to close all frames whenever a single frame closes you can do the following: You could use a window listener and call System.exit (0); …

      Java Program to determine when a Frame or Window is closing in Java

      To determine when a Window is closing in Java, use the WindowListener, which is the listener interface for receiving window events..

      WindowListener listener = new WindowAdapter() < public void windowClosing(WindowEvent evt) < Frame frame = (Frame) evt.getSource(); System.out.println("Closing = "+frame.getTitle()); >>;

      Above, we have used the windowClosing() method, which is invoked when a window is in the process of being closed −

      public void windowClosing(WindowEvent evt)

      The following is an example to determine when a Frame or Window is closing in Java −

      Example

      package my; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; public class SwingDemo < public static void main(String args[]) throws BadLocationException < JFrame frame = new JFrame("Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); WindowListener listener = new WindowAdapter() < public void windowClosing(WindowEvent evt) < Frame frame = (Frame) evt.getSource(); System.out.println("Closing = "+frame.getTitle()); >>; Container container = frame.getContentPane(); JTextPane pane = new JTextPane(); SimpleAttributeSet attributeSet = new SimpleAttributeSet(); StyleConstants.setItalic(attributeSet, true); StyleConstants.setForeground(attributeSet, Color.black); StyleConstants.setBackground(attributeSet, Color.orange); pane.setCharacterAttributes(attributeSet, true); pane.setText("This is a demo text!"); JScrollPane scrollPane = new JScrollPane(pane); container.add(scrollPane, BorderLayout.CENTER); frame.setSize(550, 300); frame.addWindowListener(listener); frame.setVisible(true); > >

      The output is as follows. The following is visible on Console −

      Output

      Java — close fxml window by code, javafx, If you don’t want to overspread you your controller with fxml linked methods you can do something like this: You have to give it a fx:id. …

      Источник

      Java close this window

      Learn Latest Tutorials

      Splunk tutorial

      SPSS tutorial

      Swagger tutorial

      T-SQL tutorial

      Tumblr tutorial

      React tutorial

      Regex tutorial

      Reinforcement learning tutorial

      R Programming tutorial

      RxJS tutorial

      React Native tutorial

      Python Design Patterns

      Python Pillow tutorial

      Python Turtle tutorial

      Keras tutorial

      Preparation

      Aptitude

      Logical Reasoning

      Verbal Ability

      Company Interview Questions

      Artificial Intelligence

      AWS Tutorial

      Selenium tutorial

      Cloud Computing

      Hadoop tutorial

      ReactJS Tutorial

      Data Science Tutorial

      Angular 7 Tutorial

      Blockchain Tutorial

      Git Tutorial

      Machine Learning Tutorial

      DevOps Tutorial

      B.Tech / MCA

      DBMS tutorial

      Data Structures tutorial

      DAA tutorial

      Operating System

      Computer Network tutorial

      Compiler Design tutorial

      Computer Organization and Architecture

      Discrete Mathematics Tutorial

      Ethical Hacking

      Computer Graphics Tutorial

      Software Engineering

      html tutorial

      Cyber Security tutorial

      Automata Tutorial

      C Language tutorial

      C++ tutorial

      Java tutorial

      .Net Framework tutorial

      Python tutorial

      List of Programs

      Control Systems tutorial

      Data Mining Tutorial

      Data Warehouse Tutorial

      Javatpoint Services

      JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

      • Website Designing
      • Website Development
      • Java Development
      • PHP Development
      • WordPress
      • Graphic Designing
      • Logo
      • Digital Marketing
      • On Page and Off Page SEO
      • PPC
      • Content Development
      • Corporate Training
      • Classroom and Online Training
      • Data Entry

      Training For College Campus

      JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
      Duration: 1 week to 2 week

      Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

      Источник

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