event

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.

Ilias Tsagklis

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button