Academic Java    Java Tutorial  >  Swing  >  WindowListener

WindowListener Example

Java WindowListener EXAMPLE output The WindowListener listens for seven types of event. When an event occurs the listener activates an appropriate method.

Because the listener is an interface each of its seven methods must be implemented in the program using it, as we have done in this WindowListener example.
// WindowListener Example
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

class WindowListenerExample {

   public static void main(String[] args) {

      JFrame f = new JFrame();

      f.addWindowListener(new WindowListener() {

         public void windowClosing(WindowEvent e) {
            System.out.println("Window Closing");
         }
         public void windowClosed(WindowEvent e) {
            System.out.println("Window Closed");
         }
         public void windowIconified(WindowEvent e) {
            System.out.println("Window Iconified");
         }
         public void windowDeiconified(WindowEvent e) {
            System.out.println("Window Deiconified");
         }
         public void windowOpened(WindowEvent e) {
            System.out.println("Window Opened");
         }
         public void windowActivated(WindowEvent e) {
            System.out.println("Window Activated");
         }
         public void windowDeactivated(WindowEvent e) {
            System.out.println("Window Deactivated");
         }
      });

      JLabel label = new JLabel("minimize the frame, observe",JLabel.CENTER);
      f.getContentPane().setBackground(Color.orange);
      f.getContentPane().add(label);

      f.setSize(300,200);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setVisible(true);

   }

}