-2

For moderators: Please see the comments of this answer: stackoverflow.com/a/16388697/1574975

I'm trying to detect when a user is done using a client program with a GUI so that when they close the JFrame for example by Xing it, I can then close the socket connections.

But I'm unable to make anything happen when user closes JFrame. I was informed that I need to use WindowListener with my JFrame but it doesn't seem to work. My class extends JFrame and here is part of the constructor setting up the JFrame:

        this.setContentPane(pane);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setVisible(true);
        final JFrame thisFrame = this;
        thisFrame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosed(WindowEvent e) {
                System.out.println("User has closed window");
            }
        });
    }

The println inside doesn't get printed which is why I think it doesn't work. Am I doing it right or do I need to do something additional?

Faahmed
  • 375
  • 4
  • 21

1 Answers1

3

windowClosed won't be called because the JVM has been closed in response to the setDefaultCloseOperation been set to JFrame.EXIT_ON_CLOSE.

Use windowClosing instead or change the defaultCloseOperation

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366