Java Swing adding Action Listener for EXIT_ON_CLOSE
Asked Answered
P

4

35

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?

Patin answered 30/4, 2013 at 8:58 Comment(0)
O
72

Try this.

addWindowListener(new WindowAdapter()
{
    @Override
    public void windowClosing(WindowEvent e)
    {
      System.out.println("Closed");
      e.getWindow().dispose();
    }
});
Overskirt answered 30/4, 2013 at 9:4 Comment(0)
E
3

Another possibility could be to override dispose() from the Window class. This reduces the number of messages sent around and also works if the default close operation is set to DISPOSE_ON_CLOSE.

Concretely this means adding

@Override
public void dispose() {
    System.out.println("Closed");
    super.dispose();
}

to your class MyGUI.

Note: don't forget to call super.dispose() as this releases the screen resources!

Emblazonry answered 26/2, 2016 at 14:37 Comment(0)
O
1

Write this code within constructor of your JFrame:

this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new java.awt.event.WindowAdapter() {
    @Override
    public void windowClosing(java.awt.event.WindowEvent e) {
        System.out.println("Uncomment following to open another window!");
        //MainPage m = new MainPage();
        //m.setVisible(true);
        e.getWindow().dispose();
        System.out.println("JFrame Closed!");
    }
});
Ossetia answered 30/8, 2017 at 6:52 Comment(1)
this is so useful, it solves my problem as well.Newfashioned
V
0

Window Events: There is the complete program, hope it will help you. public class FirstGUIApplication {

public static void main(String[] args) {
    //Frame
    JFrame window = new JFrame();
    //Title:setTitle()
    window.setTitle("First GUI App");
    //Size: setSize(width, height)
    window.setSize(600, 300);
    //Show: setVisible()
    window.setVisible(true);
    //Close
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.addWindowListener(new WindowAdapter() {
        

        @Override
        public void windowClosing(WindowEvent e) {
            super.windowClosing(e); 
            JOptionPane.showConfirmDialog(null,"Are sure to close!");
        }

        @Override
        public void windowOpened(WindowEvent e) {
            super.windowOpened(e); 
            JOptionPane.showMessageDialog(null, "Welcome to the System");
        }
        
    });
   
}

}

Vince answered 29/4, 2020 at 12:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.