Tuesday, October 18, 2011

Closing a Frame in Java AWT

To close a frame in AWT, you need to define a WindowAdapter object that will call the methods you want when the close button will be clicked. If it often beneficial to declare this new class as a nested type of the frame, since it could access the frame's methods and members.

To practically close the window, you must first make it invisible to the user and then free all the resources it occupies.
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MyFrame extends Frame 
    public class CloseWindowEvent extends WindowAdapter 
        public void windowClosing(WindowEvent we)
            //Make the frame invisible
            //Free all resources
            //If you also want to close the program,uncomment bellow
    public MyFrame(String title)
        this.add(new Label("Click X to Close"));
        //Adds the listener to the class
        this.addWindowListener(new CloseWindowEvent());

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger