How do I handle a window closing event?

Bookmark this example!  
Category: javax.swing, viewed: 740 time(s).

Here you'll see how you can handle the window closing event of a JFrame. What you need to do is add a WindowListener to the frame instance and implement the windowClosing() method.

 
package org.kodejava.example.swing;
 
import java.awt.Button;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
 
import javax.swing.JFrame;
 
public class WindowClosingExample extends JFrame {
    public static void main(String[] args) {
	WindowClosingExample frame = new WindowClosingExample();
	frame.setSize(new Dimension(200, 200));
	frame.add(new Button("Hello World"));
 
	//
	// Add window listener by implementing WindowAdapter class to the 
	// frame instance. To handle the close event we just need to implement
	// the windowClosing() method.
	//
	frame.addWindowListener(new WindowAdapter() {
 
	    @Override
	    public void windowClosing(WindowEvent e) {
		System.exit(0);
	    }
	});
 
        //
        // Show the frame
        // 
	frame.setVisible(true);
    }
}
 
 
Can't find what you are looking for? Join our FORUMS and ask some questions!
Firefox 2
Google

100 Top & Latest

GetJava Download Button

Locations of visitors to this page
eXTReMe Tracker
visitor stats