JFrame On Close Operation
Asked Answered
V

3

18

I was wondering if there is a way, by clicking on the "X", to let the program perform some code before closing the JFrame. The setDefaultCloseOperation() method takes only an integer.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Venturesome answered 6/5, 2012 at 4:39 Comment(0)
T
13

You might be interested in using a WindowListener. The WindowListener tutorial.

Temperament answered 6/5, 2012 at 4:40 Comment(2)
Thank you, very much. Thats just what im after.Venturesome
Or you can use WindowAdapter as convenience for creating listener objects.Bullock
C
23
this.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e){
                    int i=JOptionPane.showConfirmDialog(null, "Seguro que quiere salir?");
                    if(i==0)
                        System.exit(0);//cierra aplicacion
                }
            });
Cathexis answered 2/11, 2013 at 6:25 Comment(0)
G
16

@Jeffrey has a good answer, but you should consider what you're trying to do. If you really want to do something upon the closing of a frame, then a WindowListener is the way to go. However, if you're looking for a place to do some cleanup and graceful shutdown stuff, then you probably want a shutdown hook instead. Using a WindowListener, the code will only be triggered, as you said, by the user "clicking on the X". But what if the user starts the app in the foreground of a terminal and kills it with Ctrl+C? What if the user kills the process from the command line or from a task manager?

Guenna answered 6/5, 2012 at 4:48 Comment(3)
Wow, thank you for you reply. Im using this to save some data upon closing the frame.Venturesome
@Sanjay: I chose to link jdk6 because 1) in my experience, more people are still using 6 than 7, and 2) Runtime.addShutdownHook() didn't change a lick between 6 and 7.Guenna
okay,point taken :) but I usually prefer to link to the latest docs whatsoever !Lennon
T
13

You might be interested in using a WindowListener. The WindowListener tutorial.

Temperament answered 6/5, 2012 at 4:40 Comment(2)
Thank you, very much. Thats just what im after.Venturesome
Or you can use WindowAdapter as convenience for creating listener objects.Bullock

© 2022 - 2024 — McMap. All rights reserved.