Java Implementing WindowListener Interface to Close GUI Window

Implementing WindowListener Interface to Close GUI Window:

This code is continuation of this tutorial to add button to awt window. Here I handle windowClosing event to close our previously built window. Since we have implemented WindowListener interface we must implement all of its methods otherwise we’ll get compile error. Here we just need the windowClosing so we use that leave the other methods empty.

In order to register the event listener with Frame we have to add windowListener the frame ( Line Number: 31 ).

Diff with the code of adding button to awt window:

window listener interface implementation
window listener interface implementation


Code Implement WinowListener to Close Window:

import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

 * Created by asif on 8/13/2015.
public class SimpleAwtGui implements WindowListener {

    // Declare a Frame type variable
    Frame frame;
    Button button;

    public SimpleAwtGui(){
         // Create Frame Object and pass in the Frame Name / title
        frame = new Frame("AWT GUI EXAMPLE");
        button = new Button("I am here Click Me");

     * Not necessary but good practice all codes inside this can be written inside main
    public void showFrame(){
        // set the size of the window
        frame.setSize(400, 400);

        // set the layout for the window
        frame.setLayout(new FlowLayout());

        // Register the event listener to the frame

        // Add the button component to frame otherwise button won't show

        // set the frame visible otherwise nothing will be shown

    public static void main(String [] args){

        // Create an instance of SimpleAwtGui
        SimpleAwtGui window = new SimpleAwtGui();

        // call the showFrame() function to display the window


    public void windowOpened(WindowEvent e) {


    public void windowClosing(WindowEvent e) {

    public void windowClosed(WindowEvent e) {


    public void windowIconified(WindowEvent e) {


    public void windowDeiconified(WindowEvent e) {


    public void windowActivated(WindowEvent e) {


    public void windowDeactivated(WindowEvent e) {


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s