Gets the window ancestor of an event object. - Java java.awt

Java examples for java.awt:Container

Description

Gets the window ancestor of an event object.

Demo Code


//package com.java2s;
import java.awt.Component;

import java.awt.Window;
import javax.swing.JComponent;
import javax.swing.JPopupMenu;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object eventSrc = "java2s.com";
        System.out.println(getWindowAncestor(eventSrc));
    }/*  w w w. j ava 2s .  c om*/

    /**
     * Gets the window ancestor of an event object.
     * <p>
     * This presumes that eventSrc is some type of component.  This is provided as a convenience because the event source
     * for an Action is an Object, but is almost exclusively a component.
     * <p>
     * This differs from the SwingUtilities method, in that it will continue following the invoker of a JPopupMenu.
     * This is very useful since there are typically a significant number of actions in the Menu bar.
     * @param eventSrc The object to get the ancestor of.
     * @return The ancestor window of the eventSrc object, or null if no ancestor could be found.
     */
    public static Window getWindowAncestor(Object eventSrc) {
        if ((eventSrc == null) || (eventSrc instanceof Window)) {
            return (Window) eventSrc;
        } else {
            Component parent = null;

            if (eventSrc instanceof JPopupMenu) {
                parent = ((JPopupMenu) eventSrc).getInvoker();
            } else if (eventSrc instanceof JComponent) {
                parent = ((JComponent) eventSrc).getParent();
            }

            return getWindowAncestor(parent);
        }
    }
}

Related Tutorials