Closing a Swing App with Window Closing Event With Dialogs On Close

A while back I started a thread discussing how to neatly close a Swing app using both the standard window "X" button and a custom action such as a File menu with an Exit menu item. Ultimately, I came to the conclusion that the cleanest solution in many cases is to use a default close operation of JFrame.EXIT_ON_CLOSE and in any custom actions manually fire a WindowEvent with WindowEvent.WINDOW_CLOSING. Using this strategy, both the "X" button and the custom action act in the same manner and can be successfully intercepted by listening for a window closing event if any cleanup is required; furthermore, the cleanup could use dialogs to prompt for user actions without any ill effects.
I did, however, encounter one oddity that I mentioned in the previous thread. A dialog launched through SwingUtilities.invokeLater in the cleanup method would cause the app to not shutdown. This is somewhat of an academic curiosity as I am not sure you would ever have a rational need to do this, but I thought it would be interesting to explore more fully. Here is a complete example that demonstrates; see what you think:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CloseByWindowClosingTest {
     public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    launchGUI();
     private static void launchGUI() {
          final JFrame frame = new JFrame("Close By Window Closing Test");
          JPanel panel = new JPanel();
          panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
          JButton button1 = new JButton("No Dialog Close");
          JButton button2 = new JButton("Dialog On Close");
          JButton button3 = new JButton("Invoke Later Dialog On Close");
          button1.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    postWindowClosingEvent(frame);
          button2.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(frame, "Test Dialog");
                    postWindowClosingEvent(frame);
          button3.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    SwingUtilities.invokeLater(new Runnable() {
                         public void run() {
                              JOptionPane.showMessageDialog(frame, "Test Dialog");
                    postWindowClosingEvent(frame);
          panel.add(button1);
          panel.add(button2);
          panel.add(button3);
          frame.setContentPane(panel);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.addWindowListener(new WindowAdapter() {
               @Override
               public void windowClosing(WindowEvent event) {
                    System.out.println("Received Window Closing Event");
          frame.setVisible(true);
     private static void postWindowClosingEvent(JFrame frame) {
          WindowEvent windowClosingEvent = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING);
          frame.getToolkit().getSystemEventQueue().postEvent(windowClosingEvent);
}An additional note not in the example -- if in the button 3 scenario you were to put the window closing event posting inside the invoke later, the app then again closes. However, as implemented, what is it that causes button 3 to not result in the application closing?
Edited by: Skotty on Aug 11, 2009 5:08 PM -- Modified example code -- added the WindowAdapter to the frame as a window listener to show which buttons cause listeners to receive the window closing event.

I'm not sure I understand why any "cleanup" code would need to use SwingUtilities.invokeLater() to do anything. Assuming this "cleanup method" was called in response to a WindowEvent, it's already being called on the EDT.
IIRC, my approach to this "problem" was to set the JFrame to DO_NOTHING_ON_CLOSE. I create a "doExit()" method that does any cleanup and exits the application (and possibly allows the user to cancel the app closing, if so desired). Then I create a WindowListener that calls doExit() on windowClosingEvents, and have my "exit action" call doExit() as well. Seems to work fine for me.

Similar Messages

  • Java Swing apps cause Windows 2K to hang

    I have an IBM clone machine running a P4 and Windows 2k that hangs whenever I try to exit out of a window in a Java swing app. Whether the window is the main application window or a menu window instantiated by the application to be a child of the main window, does not matter. It hangs regardless. I have tried multithreaded apps and they do not cause my windows machine to hang. Neither do simple swing apps. But any multithreaded swing app causes it to hang. JEdit causes it. Forte causes it. I am running Java 1.4.1. Thanks for any help in this.

    Freezes under Java 1.4.1 with Windows
    Posted on Dec 14, 2002 - 02:57 PM by slava
    Installation This is turning into a FAQ, so I thought I'd post it on the community site. A lot of people have complained that jEdit can hard freeze their windows system after upgrading to Java 1.4.1. If you experience this, the problem is not with jEdit, but with your video driver. Updating the driver to the latest version should solve the problem; downgrading to Java 1.4.0 might also work.
    http://community.jedit.org/modules.php?op=modload&name=news&file=article&sid=190&mode=thread&order=0&thold=0

  • Testing SWING app with no user interaction

    Hi,
    I have a small SWING application, it contains a few text fields and a
    button. I want to test this without human interaction. For buttons, I tried the button.doClick() but it did not do anything! And for the text fields, I can't figure out how to do it. I am relatively new to SWING, I would appreciate your help so much.
    Thanks,
    Ann

    It may not be what you want, but why can't you simply have the button call a method when pressed. That way, in your test code you can simply call that method.
    button.addActionListener( new ActionListener() {
         public void actionPerformed( ActionEvent e ) {
              doAction();
    // Debug
    if (DEBUG) {
      doAction();
    }Jonathan

  • Swing app can't connect to DB outside jDev

    I am using jDeveloper 11.1.1.3 and have create a simple swing app with a Model and View project that connects to DB. Everything runs fine inside the IDE but when i try to execute the program outside of jDeveloper i get a null password error when it tries to access my DB. I have created the connection in application resources and have checked the 'Save Password' option. I am executing the command from a .bat file, the same command jDev uses to launch the main form inside the IDE. The form displays and the buttons work but it will not connect.
    I tried to enter the password in the connections.xml file but the main form will not load if i do this.
    What am i missing here?
    Thanks a lot.
    Edited by: user10378872 on Feb 17, 2011 8:03 AM
    Edited by: user10378872 on Feb 17, 2011 8:03 AM
    Edited by: user10378872 on Feb 17, 2011 8:06 AM

    Hello !!
    He tenido problemas con PERSISTENCIA en NETBEANS 6.1 cuando trabajo en modo grafico. (Your same problem ! ).
    Hoy por fin lo pude solucionar. La solucion:
    En la clase principal que contine el metodo MAIN, en mi caso ContaApp.java busque el metodo " public static void main(String[] args) "
    en este metodo metodo se lanza la aplicacion en la linea:
    ESTAS 2 LINEAS SE DEBEN COLOCAR ANTES DE LANZA EL METODO launch( INDICADO MAS ABAJO.
    // This is the solution !!!
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("contabilidad");
    EntityManager em = emf.createEntityManager();
    // solution end
    // este es el metodo que se lanza autmaticamente (class method)
    launch(ContaDianApp.class, args);
    Y ESO ES TODO. TU PUEDES COLOCAR TU CONEXION NORMAL EN CUALQUIER PARTE DE TU CODIGO. ES IMPORTANTE VOLVER A INSTANCIAR LA PERSISTENCIA EN TU CODIGO. ES DECIR, QUE MAS ADELANTE NECESITAS VOLVER A COLOCAR:
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("contabilidad"); // contabilidad en mi caso, tu lo debes cambiar.
    EntityManager em = emf.createEntityManager();
    Cualquier inquietud te puedes comunicar conmigo al email: [email protected]
    saludos,
    Luis Carlos

  • Office Mobile apps for Windows 10 are here

    Office Mobile apps for Windows 10 are hereToday, we’re pleased to announce the availability of the Office Mobile apps on Windows 10—bringing us one step closer to our vision of reinventing productivity. Customers can immediately download and install the apps from the new Windows Store in190 countries.The Office Mobile apps—Word, Excel, PowerPoint and OneNote—are built from the ground up for touch, offer the familiar experience that Office customers expect, and deliver the capabilities people need for on-the-go productivity on Windows 10 tablets and small screen devices. Across each of the apps, customers will appreciate full fidelity viewing of their Office documents, knowing edits and changes made on any device will render perfectly across all their devices. Tightly integrated with OneDrive, the Office Mobile apps are fully cloud...
    This topic first appeared in the Spiceworks Community

    Hi grldsndrs,
    Did you mean that you want to devleoping an VSTO add-in? As far as I know, it supports developing in Visual Studio 2013 and it is not relative to the operater system.
    You can get more detail about it from link below:
    Configuring a Computer to Develop Office Solutions
    Hopt it is helpful.
    Regards & Fei
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Catching window closing events from JFrame

    I'm having problems catching windowClosing() events from a JFrame (just doesn't get to my event listener it would seem!).
    I register and setup a window listener in the constructor of my JFrame class. Prior to this I set the default close operation as DO_NOTHING_ON_CLOSE (as you're suppose to if tyou want to handle window closing events).
    When user clicks on x (window terminate) button (in WIN systems), nothing is dispatched to my event listener. Any ideas?
    Extract from constructor:
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    addWindowListener(new MainWindowListener(this));
    MainWindowListener looks as follows (EDImemConvert extends JFrame):
    class MainWindowListener extends WindowAdapter
    private EDImemConvert f;
    public MainWindowListener(EDImemConvert f)
    this.f = f;
    public void windowClosing(WindowEvent e)
    System.out.println("gets here...");
    f.ReturnResources();
    f.dispose();
    System.exit(0);
    }

    This works for meimport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
      public Test() {
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent we) { System.exit(0); }
        setSize(300,300);
        setVisible(true);
      public static void main(String args[]) { new Test(); }
    }Normally, I just use this line
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    instead of adding a listener. It will clean up everything nicely.

  • Detect window closing event in AIR application

    How do I detect the window closing event in an AIR app? Tried
    the following.
    deactivate and windowDeactivate events in the
    WindowedApplication tag.
    addEventListener(Event.CLOSING, onClose);
    addEventListener(AIREvent.APPLICATION_DEACTIVATE onClose);
    addEventListener(AIREvent.WINDOW_DEACTIVATE, onClose);
    None of them seem to work.
    Any ideas?
    Thanks
    CS

    The following works for me:
    <mx:WindowedApplication xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute"
    closing="traceEvent(event)"
    windowDeactivate="traceEvent(event)"
    applicationDeactivate="traceEvent(event)">
    <mx:Script>
    <![CDATA[
    public function traceEvent(event:Event):void{
    trace(event.type);
    ]]>
    </mx:Script>
    </mx:WindowedApplication>
    As does:
    <mx:WindowedApplication xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute"
    applicationComplete="init()">
    <mx:Script>
    <![CDATA[
    import mx.events.AIREvent;
    public function init():void{
    this.addEventListener(Event.CLOSING, traceEvent);
    this.addEventListener(AIREvent.WINDOW_DEACTIVATE,
    traceEvent);
    this.addEventListener(AIREvent.APPLICATION_DEACTIVATE,
    traceEvent);
    public function traceEvent(event:Event):void{
    trace(event.type);
    ]]>
    </mx:Script>
    </mx:WindowedApplication>

  • Identify Frame generating 'closed'-event

    I have a jSplittedPane with a jTree on the left, a JDesktopPane on the right.
    When i select an item in the tree on the left, an jInternalFrame (application) is added (and displayed) on the jDesktopPane.
    I can switch to any item (app) at any moment by selecting other items.
    I have added a 'closed'-propertylistener to each frame added on the jDesktopPane.
    myFrame.addPropertyChangeListener("closed", new closeInternalFrame()); When i close a frame (app) on the jDesktopPane, the listener is triggered and i can do some actions
         class closeInternalFrame implements PropertyChangeListener {
            public void propertyChange(PropertyChangeEvent e) {
                  setCurrentEvent(e);
                  deActivateApplication();
            }To identify the jInternalFrame which triggers the closed-event, i do a test on the 'source' of the event
            if ((getCurrentEvent().getSource() instanceof myApp_x.myAppConstructor)){
                this.myApp_x = null;
                removeFromActiveApplicationList("Application_x");
            }This works nicely but... now comes the tricky part:
    It does not work when i open 2 jInternalFrames using the same class/constructor...
    Question:
    Is there any other way to 'identify' the jInternalFrame which triggers the 'closed'-event?
    I can 'name' my jInternalFrame but i cannot test it when the event is triggered...
            myFrame.setName("Frame1");

    Why aren't you using <tt>InternalFrameListener#windowClosed / windowClosing</tt>?
    db

  • How do I find the root cause of a NetConnection closed event?

    Hi,
    I am maintaining a large project developed in Flex/Actionscript.
    The application is using tunneling (RTMPT), and we often get Netconnection "closed" events.
    There is no problem with the physical network.
    I think the event may be caused by either a TCP/HTTP/RTMP event, or may be caused by
    some function in the client calling close() on the connection.
    How can I find the root cause of the "closed" event being thrown?
    Thanks,
    David

    Thanks for the information.  It is helpful but it seems there must be a specification of
    what the client side is expecting, independent of any server implementation. 
    When I say client side, I mean the Adobe communication libraries.
    Where is the specification or source code for how the client libraries treat HTTP tunneled requests and responses?
    One question in particular:  How does the client side library treat a
       Connection: Keep-Alive
    versuse
       Connection:close
    HTTP header setting?

  • Swing application with network event handling

    Hello, hope this is the right place for this post. I'm the design phase of a client application in java which talks to a remote server written in C via sockets. I have a design problem: I want my Swing app to have a GUI with buttons and all for normal activities, which activities report to the server, and I want the client to react to server calls anytime without interrupting normal GUi activities. Plus, all must work together, so I would prefer having a single thread for the app. (Think of an IRC client: the user uses the GUI for activities and sendim messages, and meanwhile the client listens for messages from the server and display them as they arrive). My question is: is this possible?
    I have something like (in pseudo-java):
    classMyApp extends JFrame {
      public MyApp() {
        // Manages and create the GUI
        NetHandler h = new NetHandler(this);
        h.connect();
        while(true) {
          h.pollNetEvents();
    class NetHandler {
      private BufferedReader iStream;
      private PrintWriter oStream;
      private MyApp app;
      public NetHandler(MyApp a) {
        app = a;
        Socket socket = createSocket(ip, port);
        iStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        oStream = new PrintWriter(socket.getOutputStream());
        handshakeWithServer(); // Login & Password
      public pollNetEvents() {
        try {
          String s;
          for (;;) {
            s = iStream.readLine();
            if (s.equals("") == false)
              break;
            else
              app.parseCommand(s);
        catch (IOException e) {
          app.sendMessage("Error in pollNetEvent: " + e);
    }Roughly, something like this. With this solution the GUI works, but I cannot get the message the server sends.
    I hope my message is clear enough. Can anybody help me with the design of my app? Thanks a lot.
    Fabio.

    You might consider posting this in the Swing forum. You might get a more complete response there, but here are my first thoughts.
    -- I think you will end up wanting to use multiple threads, but only one thread will update the UI. For more about threading in Swing, see this tutorial: http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
    and maybe also here: http://www.sourcebeat.com/TitleAction.do?id=10 (look at the sample chapter on Threads)
    -- For the polling code ...
    Of course, if you use the classes provided for client/server communication described below, you don't need to write your own polling code. You may still wish worry about threading so that your UI remains responsive and does not encounter major issues: http://java.sun.com/developer/JDCTechTips/2005/tt0419.html#1
    -- Updates to the UI from thread(s) that are not on the Event Dispatch Thread (the one that controls the UI) must be posted using the SwingUtilities methods, such as invokeLater
    Message was edited by:
    pthorson

  • Swing app in JDK6 continues to rendering slow in Windows Terminal Server

    Hi,
    Because Swing apps create interfaces internally and not using default OS APIs,
    when running into a Windows Terminal Server client, there is no way to optimize
    rendering. Windows Terminal Server and Linux FreeNX use a mechanism to send
    to client only commands to render the windows. But, because the way Swing works,
    not totally integrated to OS APIs, it's not possible for terminal servers to do this,
    and these servers render Swing like images, something like VNC do, very slower than.
    I have tested native apps and AWT apps, and the difference is very significant,
    something like 50-70% faster.
    Is there some project in Swing APIs or java.net open-sources to better this?

    We are also seeing this issue with a Compiere implementation. With 10 distributed sites across the US, our client wanted to use Windows Terminal Services to simplify the client desktop management of the Swing application.
    But performance is terrible...and screen painting issues a real problem. We are also on JDK5 still, so I'm discouraged to see that JDK6 doesn't appear to offer much improvement?
    Is there any project afoot to address this issue for installations using terminal services?
    Thanks,
    Peter

  • NetConnection.Connect.Closed event not triggered in Vista FF3 when in fullscreen mode

    Hello Pals -
    I'm trying to handle the net connection drop and provide some kind of visual cue to user. For this I'm listening to NetConnection.Connect.Closed event and when its triggered, I take further steps. The events are triggered in Vista FF3(window mode)/IE7 but in Vista FF3 full screen mode, the event is not triggered. I forcefully disconnect the network cable to see the NetConnection.Connect.Closed event is triggered.
    I have following piece of code to listen to the event,
    nc = new NetConnection;
    nc.addEventListener(NetStatusEvent.NET_STATUS, onStatus, false, 0, true);
    nc.connect();
    public function onStatus(event:NetStatusEvent):void {
    trace("Status " + event.info.level + " : " + event.info.code);
    The function onStatus should be called whenever there is a status change in net connection. The events are not triggered in Vista FF3 full screen mode. Please share your views/ideas about this here. Thanks in advance. Please let me know incase more information is required.

    The problem decribed as above was caused by a fragile and eventually broken soldered connection on the curcuit board. My local dealer replaced the curcuit board and everything works fine again.
    I still wonder how that happend. I did not try to bend my MacBook and it did not fall of my desk.
    Thanks for reading.

  • How do I stop iPhoto from repeatedly closing Event title boxes when I am in the middle of entering a title?

    How do I stop iPhoto from repeatedly closing Event title boxes when I am in the middle of entering a title?
    This problem started several months ago. I have tried typing more slowly and typing faster; neither help.
    It now takes me about four attempts to complete a title of about twelve characters, achieving about three characters on each attempt.
    I am running iPhoto 9.4.3 on OS X 10.8.3 on a 2.93 GHz Intel Quad-Core i7 iMac with 12 GB of DDR3 memory.

    As a Test:
    Hold down the option (or alt) key and launch iPhoto. From the resulting menu select 'Create Library'
    Import a few pics into this new, blank library. Is the Problem repeated there?

  • How to separate different views and parts of a single line of business(LOB) universal app for windows 8.1 with many users.

    Hello am an intermediate Windows Phone/Store Developer. Am currently in the process of implementing a LOB app that will have three different types users, an admin, a student, a teacher . Depending on how a user logs in i would like certain pages to be exposed
    to them and the rest to be hidden. The app will also store data temporally on a local db then sync regularly to an azure database(Can the recent entity framework 7 that supports store/phone apps allow code first databases or are there features still not fully
    accessible in WinRT apps)...This i believe can handle but also kindly point me out to existing implemented resources/examples i will appreciate very much.
    What am finding problematic is how to consume different app data stored by various users logged in for these different views. Will i need an asp web api is it really necessary cause i want to avoid it cause i have about three months to do it. I do not want
    to create three different apps and one ASP Web AP,  i want one single app and an api if possible, i know windows usually sandboxes apps hence app to app communication will be hard if not impossible. So my question is, is it possible to implement different
    user session management with a login (Windows Live ID) which i can abstract various parts of the app from them depending on the users login id in the app. E.g How can an admin logged in the same app as the student have access rights to certain pages in the
    app that a student will not see. How do i route different users to certain pages and can isolated storage store these persisting as a setting.
    How can i know which login id belongs to which of the three users? How do i then assign different access to different controls of the app with their id,provide custom views routes,access right,session management. I think i can do these without an ASP Web
    API is It wise? Building pages in the apps is easy but i want users to see different views of the app instead of one standard app depending on there login id, how can the NAVIGATION URI be used here. How can azure and features like active directory,azure mobile
    services. I know i have repeated the same things over and over and these might be complex for a free advise but as a windows dev these is my one stop shop. Any one with a view on how to approach these kindly show me the best directions. Thanks guys in advance.

    I suggest you have a look at this sample.
    https://code.msdn.microsoft.com/windowsapps/ListView-Interaction-ac044c3c. MainPage provides the framework to hold the content. At runtime, we create the Scenario collections and then bind to control. This approach can help you determine the type of users
    and provide some appropriate pages at runtime.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. Click HERE to participate
    the survey.

  • How to get the closing event (not closed) of Dialog control

    Hi All,
    I have one requirement, that I have to close the Dialog box in an animated way like on clicking of the Dialog close button the popup has to close from top to bottom in a slide effect.
    sap.ui.commons.Dialog
    When I tried closed method of Dialog, it is calling only after dialog box closed but, I need the closing event rather closed event.
    I am putting a UI5 view in Dialog as I need some custom/dynamic content in the dialog.
    Please suggest the solution for this.
    Thanks & Regards,
    Pavan Thirunamala,
    [Moderator Message - Please do not provide contact information like Phone Number etc in the discussion message. It has been removed.]
    Message was edited by: Chandrashekhar Mahajan

    JS Bin - Collaborative JavaScript Debugging&lt;/title&gt; &lt;link rel=&quot;alternate&quot; type=&quot;application/jso…
                sap.ui.getCore().getEventBus().subscribe("sap.ui","__beforePopupClose",
    function(channel, event, params)
      debugger;   
    $(params.domNode).animate({
                      opacity : 1,
                  height : 0

Maybe you are looking for

  • Facebook event overload in iOS 6 Calendar.

    I like the idea of easily having events that I am going to synced in my Calendar, but, apparently, it adds events that you've been invited to even if you haven't decided to go.  I don't need my Calendar filled with potential events, I only want the o

  • Party shuffle issue

    Hello, I'm having an odd issue occur. About a week ago, the Party Shuffle feature stopped playing more than one song. Whatever would normally point it to the next song, seems to not be in place. I updated to the new iTunes version a few weeks back, b

  • Import EPA file into portal

    Hi, I need to import EPA file into portal . Any one please tell me how can i import EPA file into portal. Thanks, Sumanth

  • Error with sales order header text

    Hi All, I am getting 3 texts from 850 IDOC on to Sales order header texts. I created 3 new textid's for them. This is working properly in Dev system and I just moved them to Test system. I created a sales order by using the IDOC. I tried to go to ord

  • Flex engine integration

    Hi All, I have EP 6.0 SP 14 & VC Patch 6 SP13 installed and integrated. I wanted to integrate the Flex server + builder with the visual composer. Have anyone done this earlier? Can some one point me to any user guide for the same? thanks in advance