Add a Window Listener using the WindowAdapter class and put your logic in its methods.