Why isn't windowClosed working?
Hi everybody,
I'm running into a problem with some code, trying to have something stop running when a window closes. However, whether I use windowClosing or windowClosed, it never seems to work. I can't figure out why, can someone help me out?
Here's a really small program that shows what's going on here--it compiles and runs fine. A word of warning if you run it though, since the windowClosed never works, the program never closes, so you have to shut the progam down manually. The code is:
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
publicclass WindowTestextends WindowAdapter{
publicstaticvoid main(String args[]){
try{
JFrame frame =new JFrame();
frame.setSize( 400, 400 );
frame.setVisible(true );
}catch( Exception e ){
e.printStackTrace();
}
}
publicvoid windowClosed( WindowEvent e ){
System.out.println("The window was closed." );
System.exit(0);
}
}
I think this is the shortest self-contained program I've ever written; I'm really proud of myself! :)
Any help anybody could give on this would be great.
Thanks!
Jezzica85
Message was edited by:
jezzica85
[2087 byte] By [
jezzica85a] at [2007-11-27 11:28:45]

# 1
See comments in code.
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class WindowTest extends WindowAdapter {
public static void main(String args[]) {
new WindowTest();
}
public WindowTest() {
try {
JFrame frame = new JFrame();
// the next two methods were missing
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(this);
// your old code continues
frame.setSize( 400, 400 );
frame.setVisible( true );
} catch( Exception e ) {
e.printStackTrace();
}
}
// window closing is used instead of windowClosed
// window closed can be used when the default close operation is set
// to DISPOSE_ON_CLOSE or HIDE_ON_CLOSE
public void windowClosing( WindowEvent e ) {
System.out.println( "The window is closing. This process can not be stopped" );
//System.exit(0);
}
}
ICE
# 3
As a minimum, this code creates the window, then exits Java when the window is closed.
import javax.swing.*;
public class Xyyyy
{
public static void main(String args[])
{
JFrame frame = new JFrame();
frame.setSize( 400, 400 );
frame.setVisible( true );
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}