Close the window in java

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.

    Источник

    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,277 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++

        Источник

        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

        • 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.

        Источник

        Close the window in java

        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

        Источник

        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.

        Источник

        Читайте также:  Examples of javascript animation
Оцените статью