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);
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.
Now, we have to exit JFrame on close. One simple way of doing this is clicking the cross button on the top right corner of the frame which closes the frame but the application or code will still be running in the background.
Use anything for setDefaultCloseOperation excepting EXIT_ON_CLOSE . Then, for the cancel button, just dispose() the window. If the application has another running thread, it won't exit. You can also hide a window by calling setVisible(false) .
The default behavior is to simply hide the JFrame when the user closes the window. To change the default behavior, you invoke the method setDefaultCloseOperation(int) . To make the JFrame behave the same as a Frame instance, use setDefaultCloseOperation(WindowConstants. DO_NOTHING_ON_CLOSE) .
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With