event
WindowListener demo
In this tutorial we will see how to use the WindowListener
. This is particularly useful when you are working with a window application and you want to monitor the state of each window. With the WindowListener
you can monitor a number of events. The opening or the closing of a window for instance. So, when a window opens or closes, the respective function will be executed, and consequently the code we want to be executed every time that specific event occurs.
In short, all you have to do in order to work with a WindowListener is:
- Create a
JFrame
window - Create a new
WindowListener
and override the methods that correspond to the events you want to monitor, e.gwindowOpened
,windowClosing
,windowClosed
,windowIconified
etc
Let’s see the code:
package com.javacodegeeks.snippets.desktop; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; public class WindowListenerDemo { private static void showUI() { JFrame jFrame = new JFrame("Window Listener"); WindowListener listener = new WindowListener() { @Override public void windowActivated(WindowEvent event) { System.out.println(event); } @Override public void windowClosed(WindowEvent event) { System.out.println(event); } @Override public void windowClosing(WindowEvent event) { System.out.println(event); System.exit(0); } @Override public void windowDeactivated(WindowEvent event) { System.out.println(event); } @Override public void windowDeiconified(WindowEvent event) { System.out.println(event); } @Override public void windowIconified(WindowEvent event) { System.out.println(event); } @Override public void windowOpened(WindowEvent event) { System.out.println(event); } }; jFrame.addWindowListener(listener); jFrame.setSize(500, 500); jFrame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { showUI(); } }); } }
This was an example on how to use a WindowListener
.