Home » Desktop Java » awt » event » WindowListener example

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

WindowListener example

With this tutorial we shall show you how to use the WindowListener interface in Java. This component can be very useful when you develop an application with many windows an many frames, and you mast have full control over window changes.

This can also be used when you want your application to behave differently depending on the window changes the user makes or simply notify the user or the system that some values of the windows have been changed.

In short, to work with WindowListener one should follow these steps:

  • Create a new WindowListener instance.
  • Override the methods that correspond to the events that you want to monitor about the windows e.g windowClosingand and customize as you wish the handling of the respective events. Now every time one of these events occurs, like when a window closes, the corresponding method will be executed.
  • Use an addWindowListener to add the WindowListener to a specific component.

Let’s take a look at the code:

package com.javacodegeeks.snippets.desktop;

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

import javax.swing.JFrame;

public class Main {

    public static void main(String args[]) {

  JFrame frame = new JFrame("Window Listener");

  WindowListener listener = new WindowAdapter() {

@Override

public void windowClosing(WindowEvent w) {

    System.exit(0);

}

  };

  frame.addWindowListener(listener);

  frame.setSize(300, 300);

  frame.setVisible(true);
    }
}

 
This was an example on how to work with WindowListener in Java.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of