How to close a Java Swing application from the code

What is the proper way to terminate a Swing application from the code, and what are the pitfalls?

I'd tried to close my application automatically after a timer fires. But just calling dispose() on the JFrame didn't do the trick - the window vanished but the application did not terminate. However when closing the window with the close button, the application does terminate. What should I do?


Asked by: Maria424 | Posted: 23-01-2022






Answer 1

Your JFrame default close action can be set to "DISPOSE_ON_CLOSE" instead of EXIT_ON_CLOSE (why people keep using EXIT_ON_CLOSE is beyond me).

If you have any undisposed windows or non-daemon threads, your application will not terminate. This should be considered a error (and solving it with System.exit is a very bad idea).

The most common culprits are java.util.Timer and a custom Thread you've created. Both should be set to daemon or must be explicitly killed.

If you want to check for all active frames, you can use Frame.getFrames(). If all Windows/Frames are disposed of, then use a debugger to check for any non-daemon threads that are still running.

Answered by: Tara852 | Posted: 24-02-2022



Answer 2

I guess a EXIT_ON_CLOSE

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

before System.exit(0) is better since you can write a Window Listener to make some cleaning operations before actually leaving the app.

That window listener allows you to defined:

public void windowClosing(WindowEvent e) {
    displayMessage("WindowListener method called: windowClosing.");
    //A pause so user can see the message before
    //the window actually closes.
    ActionListener task = new ActionListener() {
        boolean alreadyDisposed = false;
        public void actionPerformed(ActionEvent e) {
            if (frame.isDisplayable()) {
                alreadyDisposed = true;
                frame.dispose();
            }
        }
    };
    Timer timer = new Timer(500, task); //fire every half second
    timer.setInitialDelay(2000);        //first delay 2 seconds
    timer.setRepeats(false);
    timer.start();
}

public void windowClosed(WindowEvent e) {
    //This will only be seen on standard output.
    displayMessage("WindowListener method called: windowClosed.");
}

Answered by: Leonardo410 | Posted: 24-02-2022



Answer 3

Try:

System.exit(0);

Crude, but effective.

Answered by: Lily281 | Posted: 24-02-2022



Answer 4

May be the safe way is something like:

    private JButton btnExit;
    ...
    btnExit = new JButton("Quit");      
    btnExit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e){
            Container frame = btnExit.getParent();
            do 
                frame = frame.getParent(); 
            while (!(frame instanceof JFrame));                                      
            ((JFrame) frame).dispose();
        }
    });

Answered by: Julia131 | Posted: 24-02-2022



Answer 5

The following program includes code that will terminate a program lacking extraneous threads without explicitly calling System.exit(). In order to apply this example to applications using threads/listeners/timers/etc, one need only insert cleanup code requesting (and, if applicable, awaiting) their termination before the WindowEvent is manually initiated within actionPerformed().

For those who wish to copy/paste code capable of running exactly as shown, a slightly-ugly but otherwise irrelevant main method is included at the end.

public class CloseExample extends JFrame implements ActionListener {

    private JButton turnOffButton;

    private void addStuff() {
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        turnOffButton = new JButton("Exit");
        turnOffButton.addActionListener(this);
        this.add(turnOffButton);
    }

    public void actionPerformed(ActionEvent quitEvent) {
        /* Iterate through and close all timers, threads, etc here */
        this.processWindowEvent(
                new WindowEvent(
                      this, WindowEvent.WINDOW_CLOSING));
    }

    public CloseExample() {
        super("Close Me!");
        addStuff();
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                CloseExample cTW = new CloseExample();
                cTW.setSize(200, 100);
                cTW.setLocation(300,300);
                cTW.setVisible(true);
            }
        });
    }
}

Answered by: David455 | Posted: 24-02-2022



Answer 6

If I understand you correctly you want to close the application even if the user did not click on the close button. You will need to register WindowEvents maybe with addWindowListener() or enableEvents() whichever suits your needs better.

You can then invoke the event with a call to processWindowEvent(). Here is a sample code that will create a JFrame, wait 5 seconds and close the JFrame without user interaction.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ClosingFrame extends JFrame implements WindowListener{

public ClosingFrame(){
    super("A Frame");
    setSize(400, 400);
            //in case the user closes the window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            //enables Window Events on this Component
            this.addWindowListener(this);

            //start a timer
    Thread t = new Timer();
            t.start();
    }

public void windowOpened(WindowEvent e){}
public void windowClosing(WindowEvent e){}

    //the event that we are interested in
public void windowClosed(WindowEvent e){
    System.exit(0);
}

public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}

    //a simple timer 
    class Timer extends Thread{
           int time = 10;
           public void run(){
     while(time-- > 0){
       System.out.println("Still Waiting:" + time);
               try{
                 sleep(500);                     
               }catch(InterruptedException e){}
             }
             System.out.println("About to close");
    //close the frame
            ClosingFrame.this.processWindowEvent(
                 new WindowEvent(
                       ClosingFrame.this, WindowEvent.WINDOW_CLOSED));
           }
    }

    //instantiate the Frame
public static void main(String args[]){
          new ClosingFrame();
    }

}

As you can see, the processWindowEvent() method causes the WindowClosed event to be fired where you have an oportunity to do some clean up code if you require before closing the application.

Answered by: Wilson621 | Posted: 24-02-2022



Answer 7

Take a look at the Oracle Documentation.

Starting from JDK 1.4 an Application terminates if:

  • There are no displayable AWT or Swing components.
  • There are no native events in the native event queue.
  • There are no AWT events in java EventQueues.

Cornercases:

The document states that some packages create displayable components without releasing them.A program which calls Toolkit.getDefaultToolkit() won't terminate. is among others given as an example.

Also other Processes can keep AWT alive when they, for what ever reason, are sending events into the native event queue.

Also I noticed that on some Systems it takes a coupple of seconds before the Application actually terminates.

Answered by: Grace804 | Posted: 24-02-2022



Answer 8

I think, the idea is here the WindowListener - you can add any code there that you'd like to run before the thing shuts down

Answered by: Alford883 | Posted: 24-02-2022



Answer 9

In response to other comments, DISPOSE_ON_CLOSE does not seem to properly exit the application - it only destroys the window, but the application will continue running. If you want to terminate the application use EXIT_ON_CLOSE.

Answered by: Maria308 | Posted: 24-02-2022



Similar questions

java - Do not close the application after a crash

So I would like to know if it is possible to not close the application after a crash. I am doing testing on Android applications and I would like the code that would allow me to continue my test when there is a crash


Close C# form when Java application Start

I have a form (progress bar) in C# which starts on double click of .exe. I want to close the form once the java application starts. How do I achieve it? static class Program { static Form1 myForm; static void Main(string[] args) { ProcessStartInfo startInfo = new ProcessStartInfo(); // Prevents the cmd window for the batch file from showing up ...


java - How to close a view in in RCP Application?

I have a RCP Application with number of views. There is a 'Welcome' view and other views. Whenever I select 'Welcome' view, other views are closed using the code, PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().hideView(viewID); (Note : Dependency of other plug-in is added to the plug-in where 'Welcome' view is present.) The same way, I want to close 'Welcome...


java - Run Code On Application Close

This is a very common problem yet again, and yet again it seems there is no real support in E4 (but if I remember correctly, it did not work in E3 either). I want to close my database connection when the application closes. Or more general: I want to do any kind of clean up on exit. So the usual API for this is: public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {...


java - Only close JavaFX application

I am trying to make a LWJGL game run a JavaFX application and the game, then close only the JavaFX application, but doing System.exit(0) closes both windows. How can I get the desired result


java - Close application by alarm in dozen mode

I'm trying to solve strange problem. This device work only with my Application. Application is always opened. Every night i application should been closed. I added alarm for different SDK-case and it work: AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); if (SDK_INT < Build.VERSION_CODES.KITKAT) alarmManager.set(AlarmManager.RTC, time, pendingIntent); else ...


java - How to close video after stop in JavaFX application?

I'm creating an JavaFX application with Scene Builder. I added a video at the beginning. So I wanna play video before my application start in fullscreen mode. The Problem is when it is stopped I see only black screeen and nothing happened, I guess it is because video is fullscreen and it is not automatically closed. I also have a bug before the video starts, some blink of my main window .I guess it is because vide...


java - API call on application close javafx

Closed. This question needs debugging detai...


windows - IE6 generated strange worksheet name when doing export from java application

I am encountering error like test(10)[1].csv file cannot be found at C:\Documents and Settings\Ron\Local Settings\Temporary Internet Files\Content.IE5\PQ0STUVW When trying to do export of CSV file using the following codes. Anyone have any idea what could be wrong? This issue does not occur in IE7 / Firefox and is only specific to IE6. response.setContentType("applicati...


c# - Embedding Flash Player in a C++ or Java application?

I would like to embed Flash Player directly inside a C++ or Java application. I found an article that describes how to do this for C#: http://www.adobe.com/devnet/flash/articles/stock_history03.html Unfortunately, I have no experience with C#, COM or ActiveX. I need someone to translate this code to C++, allowing ...


java - How best to implement user selectable variables in web application

I have a Java based web-application and a new requirement to allow Users to place variables into text fields that are replaced when a document or other output is produced. How have others gone about this? I was thinking of having a pre-defined set of variables such as : @BOOKING_NUMBER@ @INVOICE_NUMBER@ Then when a user enters some text they can specify a variable inline ...


java - BIRT in a desktop application

Did someone ever used a BIRT report in a desktop application. I'm comming from the .NET environment and there you can use Crystal Reports to show reports in desktop apps. Is this possible with BIRT too, without having to set up a server environment? Can you give me some advice how to reach this goal? Thanks in advance.


which library better for faster java application swt or swing?

which library better for faster java application swt or swing?


java - Which is the best Open source application server?


java - Access spring bean that is exposed using http invoker from GWT application

Can I access spring bean that exposed using http invoker (server) from GWT application (client)? If so is there any example / tutorial for that?


java - How best can I isolate my application from an unreliable database?

I have a Java SOAP data service which sits on top of a Sybase database which, for reasons out of my control, has unreliable performance. The database is part of a vendor package which has been modified by an internal team and most of the issues are caused by slow response times at certain times of the day. The SOAP service provides data to a calculation grid and when I request data, I need the response time to be ...


java - Netbeans GUI Designer & Fixed-Size Application Panels

I'm having a problem, creating a fixed-size overall panel for a touchscreen GUI application that has to take up the entire screen. In a nutshell, the touchscreen is 800 x 600 pixels, and therefore I want the main GUI panel to be that size. When I start a new GUI project in NetBeans, I set the properties of the main panel for min/max/preferred size to 800 x 600, and the panel within the 'Design' view changes size. ...


How do I create a "Hello World" application in java for an iphone?

I'd like to create a basic "Hello World" style application for the IPhone using Java - can anyone tell me how?






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top