Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing adding Action Listener for EXIT_ON_CLOSE

I have a simple GUI:

    public class MyGUI extends JFrame{          public MyGUI(){            run();         }          void run(){            setSize(100, 100);            setVisible(true);            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// maybe an action listener here         }     } 

I would like to print out this message:

 System.out.println("Closed"); 

When the GUI is closed (when the X is pressed). How can I do that?

like image 987
Hamid Avatar asked Apr 30 '13 08:04

Hamid


People also ask

What is setDefaultCloseOperation JFrame Exit_on_close in Java?

Calling setDefaultCloseOperation(EXIT_ON_CLOSE) does exactly this. It causes the application to exit when the application receives a close window event from the operating system.


1 Answers

Try this.

    addWindowListener(new WindowAdapter()         {             @Override             public void windowClosing(WindowEvent e)             {                 System.out.println("Closed");                 e.getWindow().dispose();             }         }); 
like image 53
prasanth Avatar answered Sep 22 '22 12:09

prasanth