add Window Listener - Java Swing

Java examples for Swing:Screen

Description

add Window Listener

Demo Code


//package com.java2s;

import java.awt.Component;

import java.awt.Window;

import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;

import java.awt.event.WindowListener;

import javax.swing.SwingUtilities;

public class Main {
    public static void addWindowListener(final Component source,
            final WindowListener listener) {
        if (source instanceof Window) {
            ((Window) source).addWindowListener(listener);
        } else {// w  w w.ja  va2s  . c om
            source.addHierarchyListener(new HierarchyListener() {
                @Override
                public void hierarchyChanged(HierarchyEvent e) {
                    if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) == HierarchyEvent.SHOWING_CHANGED) {
                        SwingUtilities.getWindowAncestor(source)
                                .addWindowListener(listener);
                    }
                }
            });
        }
    }
}

Related Tutorials