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.

Similar Messages

  • How to catch the mouse event from the JTable cell of  the DefaultCellEditor

    Hi, my problem is:
    I have a JTable with the cells of DefaultCellEditor(JComboBox) and added the mouse listener to JTable. I can catch the mouse event from any editor cell when this cell didn't be focused. However, when I click the editor to select one JComboBox element, all the mouse events were intercepted by the editor.
    So, how can I catch the mouse event in this case? In other word, even if I do the operation over the editor, I also need to catch the cursor position.
    Any idea will be highly appreciated!
    Thanks in advance!

    Hi, bbritta,
    Thanks very much for your help. Really, your code could run well, but my case is to catch the JComboBox event. So, when I change the JTextField as JComboBox, it still fail to catch the event. The following is my code. Could you give me any other suggestion?
    Also, any one has a good idea for my problem? I look forward to the right solution to this problem.
    Thanks.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test3
    extends JFrame {
    // JTextField jtf = new JTextField();
    Object[] as = {"aa","bb","cc","dd"};
    JComboBox box = new JComboBox(as);
    public Test3() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    String[] head = {
    "One", "Two", "Three"};
    String[][] data = {
    "R1-C1", "R1-C2", "R1-C3"}
    "R2-C1", "R2-C2", "R2-C3"}
    JTable jt = new JTable(data, head);
    box.addMouseListener(new MouseAdapter() {
    // jtf.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e)
    System.out.println("-------------------JComboBox mouseclick....");
    jt.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e)
    System.out.println("-------------------JTable mouseclick....");
    // jt.setDefaultEditor(Object.class, new DefaultCellEditor(jtf));
    jt.setDefaultEditor(Object.class, new DefaultCellEditor(box));
    content.add(new JScrollPane(jt), BorderLayout.CENTER);
    setSize(300, 300);
    public static void main(String[] args) {
    new Test3().setVisible(true);
    }

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

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

  • How to trap applet window closing event?

    Hi all,
    I would like to know how could one trap the event of the browser window containing an applet being closed by the user?
    Thank you,

    Hi. this would be useful to me too.
    Trouble is, I'm not sure that you can. applet.stop( )
    and applet.destroy( ) might be called, but there is
    no guarentee that you can complete processing before
    you are terminated, especially if you need to do
    something slow, like returning state data to your
    server. And you can't stop the broswer closing.
    I know that in Javascript, you can catch and even
    stop the browser window being closed, which is how
    things like goggledocs can ask for confirmation
    before closing. (window.onbeforeunload( ) ).
    I have toyed with the idea of having a
    javascript/ajax thread in my html, to catch this
    termination, and communicate back to the server from
    java to say a document has changed, but it all seems
    rather heavyweight for such a simple task.Look at Runtime.addShutdownHook()
    You could also try using a WindowListener as well and trap the WindowClose Event.
    stop() should do very little other than invalidate the current thread/run flags
    and then exit. ie: a stop() example
    public void stop()
    task = null;
    or
    public void stop()
    running = false;
    Your run method should look for a stop condition and then exit.
    Otherwise you could be doing stop processing while run is still
    running.
    (T)

  • Window-Closing Events

    Please, clarify the sequence. When user clicks a "cancel" button on a JDialog's descedant, I make clean up and call dispose. I've hooked hide and dispose methods of the dialog and getting the followind sequence:
    disposing
    hiding
    disposing
    hiding
    That is, hide and dispose are called twice by swing. Initially, I was considering using a hook at hide or dispose for performing a clean-up action. However, doing clean-up twice is bad idea.

    Use java.awt.WindowListener and the Window.addWindowListener method (JDialog descends from Window). From the javadoc:
    void windowClosed(WindowEvent e)
    Invoked when a window has been closed as the result of calling dispose on the window.
    void windowClosing(WindowEvent e)
    Invoked when the user attempts to close the window from the window's system menu.
    I haven't tested it to see how many times it gets called, but I would guess only once.

  • How to catch window maximised event ?

    I know I need to creat class that will implement WindowListener. But what even should I catch ?? And also... I need to restrict this function... so my window can't be maximised... how do i do this ? Any hints ??? Please help.

    For the first problem you should use the componentResized() method of the ComponentListener interface: in this method, just call yourFrame.getExtendedState() and compare it with JFrame.MAXIMIZED_BOTH... that will tell you if the frame has been maximized.
    For the second point, use the same principle: after the above test, if the frame is maximized you can resize it to whatever dimension you like.
    The code would be:
          yourFrame.addComponentListener(new ComponentAdapter() {
             public void componentResized(ComponentEvent e) {
                if (yourFrame.getExtendedState == JFrame.MAXIMIZED_BOTH) {
                   yourFrame.setSize(300,300);
          });Of course, the given size is for example.
    Hope this helped,
    Regards.

  • How to fire a window closing event, not clicking the X button of the UI

    I�ve an application that uses a WindowListener for the WindowClosing event of a JFrame. When the user presses CTRL-Q I needed to fire a windowClosing for that frame, in order to detect it and take some actions in the class referencig the JFrame (this class has the windowListener).
    setDefaultCloseOperation was not good for me, so i fire the windowClosing event with the following code:
    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
        WindowEvent we = new WindowEvent(this,WindowEvent.WINDOW_CLOSING, null, 0, 0);
        this.getWindowListeners()[0].windowClosing(we);
    }Hope this is the right way to fire the event and this helps someone. If not please code a better way,
    Alonso

    Yes, that works and looks better:
    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                            
       this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    } "this" refers to the JFrame.

  • Window closeing event

    Hi all,
    I,ve created a Bank Class, that creates Atm ,s from a button in the bank
    can someone show me how to close each frame individually instead of all at once
    this is were i create the atm class
         public void actionPerformed(ActionEvent {
    if(ae.getSource( ) == b1)
    laB2.setText("Atm "+index+" now Created");
    b1.setLabel("Atm"+index);//creates atm labeled in bank     
    Atm Atm1 = new Atm(hsbc);
    //Atm1.setText("Atm"+index);
    [code\]
    Thank you very much

    Ref Above, i get the following Error,
    Hope you can Help
    Thanks Again
    public void actionPerformed(ActionEvent ae){
    if(ae.getSource( ) == b1)
    Atm Atm1 = new Atm(hsbc);
    Atm1 .addWindowListener(new vWindowAdapter()                
    public void windowClosing(WindowEvent win_eve)
    Atm1 .setVisible(false);
    [code\]
    --------------------Configuration: j2sdk1.4.0_01 <Default>--------------------
    C:\Assignment2\Ass2 Code\Assignment2.java:189: local variable Atm1 is accessed from within inner class; needs to be declared final
                                  Atm1 .setVisible(false);
                                                    ^
    C:\Assignment2\Ass2 Code\Assignment2.java:189: cannot resolve symbol
    symbol  : method setVisible  (boolean)
    location: class Assignment2.Atm
                                  Atm1 .setVisible(false);
                                                         ^
    C:\Assignment2\Ass2 Code\Assignment2.java:185: cannot resolve symbol
    symbol  : method addWindowListener  (<anonymous java.awt.event.WindowAdapter>)
    location: class Assignment2.Atm
                               Atm1 .addWindowListener(new WindowAdapter()

  • Catch a key event in JFrame

    hi,
    i am coding a GUI application for some FSM(Finite State Machine) simulation purpose. the app can load the FSM and display it. i can selecte some part of FSM and using "delete" key to delete the selected states. i did register the KeyEventListener to the the JFrame. but when i try to press the "del" key the app doesn't do anything. after few tests, i think JFrame never listene to my key event. how can i make it possible to let the JFrame to listene to my "key event"?
    Thanks~~~

    Read this, it is very useful for things like this:
    [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings
    In your case you can add a key binding to the frame's root pane, and bind the delete key to the action you want to perform.

  • How to catch menu click events from B1AddOn Wizard

    Dear Friends,
    I'm adding some custom menus to the SAP BO main menù using B1 Addon Wizard generated code, but then I don't know how to catch the events generated by the menus.
    Thank you for attention
    Massimo

    Thank you Eddy,
    I had a look at the help, but there it is not explainsed that events can be attached only to string menus!!
    It was attempting to do something wrong.
    A further question: is it possible to add new menus and related events to an existing project (I tried with new item and then B1 Addon Component, but it doesn't let me add new menus)?
    Thanks again
    Masimo

  • Frame window closing

    Hi friends,
    please help me in following situation.
    I have a frame1, where i have a button to open new frame2. this frame 2 opens some other frames.
    When i close main frame1, i want to trigger a event or execute a method on other frames. i tried window closing and window closed events from frame1 or frame2.
    frame2 and frame3 windows r just closing without any events when i close main frame1.
    frame2 and frame3 must extend JFrame not JDialog.
    thanks,

    make in each frame a lille method that calls the next frame (if there is one) and waits until he gets something in return...
    so 1 calls 2, 2 calls 3....
    3 is the last frame and shuts itself down, but first it returns a value to 2.
    then 2 knows it can return a value to 1 and closes itself...
    that's the thing i would do... but never tried it yet so dunno about the speed it goes....
    leme know if I helped you out.
    SeJo

  • Catch frame's closing event

    Hi,
    I was wondering how to accomplish this...
    How can I catch the closing event, that a user creates by clicking on the X on the top upper right of a jframe?
    I have a cancel button that calls an onCancel method, and I need to also call that onCancel method for that action.
    public void onCancel() {
       // Cancel the operation
    }Any suggestions?
    V

    I'll answer;
    myframe.addWindowListener(new WindowAdapter()
                                    public void windowClosing(WindowEvent we)
                                                     {onCancel();}
                                   });Another way would be to:
    class MyWindowListener extends WindowAdapter()
    private MyClassWithOnCancelMethod mcwocm;
    public MyWindowListener(MyClassWithOnCancelMethod moc)
       mcwocm = moc;
    public void windowClosing(WindowEvent we)
       mcwocm.onCancel();
    }And then, in your previous class:
    MyWindowListener mwl = new MyWindowListener(this);
    myframe.addWindowListener(mwl);Kinda your choice.
    ~David

  • Performing some actions before window closing in browser

    this can be done by <body onbeforeunload='delcookie()'>
    delete cookie is a javascript function where i put inthe code to delete the cookie of my page when some one closes the page or some thing else load in that window.
    this works even if window closes or some other page loads into the window. onunload can also be used it .it works in the second case only.

    Hi Sunil,
    You can retrieve the application properties in your code by:
    IWDApplicationInfo application = wdComponentAPI.getApplication().getApplicationInfo();
    String value = application.findInApplicationProperties("<property name>").getValue();
    for eg: you can retrieve expiration time as:
    application.findInApplicationProperties("sap.expirationTime").getValue();
    But expiration time is the time after which the application expires and has nothing to do with the real time
    About the application closing, as far as I know there is no event in webdynpro to capture the window closing event. So it depends on how the user closes the application. If he closes the application from within it using some button or link, then you can very well write the required code there. If he closes the browser directly, then I don't think you can handle that.
    Hope this helps,
    Best Regards,
    Nibu.

  • Mx.core.Window - prevent user from closing the window?

    Hi,
    mx.core.Window has properties 'maximizable' &
    'minimizable', but there doesn't seem to be any 'closable'
    property. In my application I'm creating another window (apart from
    the main application window) that needs to be open the whole time
    the application is running. If I can't prevent the user from
    closing the window, then I'll have to rig up some code to
    automatically re-open it if the user closes it. I'm hoping there's
    a way to prevent the user from closing the window in the first
    place though.
    I'll much appreciate any ideas - thanks :)

    Listen for the window's closing event and call
    preventDefault().

Maybe you are looking for

  • Opinions on Flex modes?

    Just curious as to which Flex mode people are finding most natural for quantizing guitar & vocals - my general feeling so far is that the mono is usually best, but I'm not too experienced with it yet. I have not found any setting that seems to be as

  • Catalogue Freezes in Photoshop Elements 12 in Windows 7 on desktop

    I  am trying to transfer Photoshop Elements 12 Catalogue to a new computer, (from W7 to W8.1) but when backing up my catalogue on W7 I get as far as 62% and Photoshop stops responding. I have repaired and checked the catalogue in Catalogue manager an

  • Charts not opening as same type chart that it was saved as

    sqld version 4 On a number of charts I have created in reports the chart opens as a different type that what I have the report defined to show. Example: create chart as combination dual y. next time sqldeveloper is started and report is run the chart

  • IPhoto Won't Let Me Import

    Every time I attempt to import pictures from a digital camera or from 'My Pictures' into iPhoto, the program quits unexpectedly. So I have never been able to use iPhoto or transfer the pictures onto my iPod.

  • Trying to run a query on 10g database using vbscript

    Hi, We have recently upgraded from oracle 8 to 10g and have been very impressed with the superb performance. However, we use vbscript applications on occasions to connect to our DB using ADO which now no longer work: Set dbUser = CreateObject("ADODB.