Java 怎么获取事件对象的窗口祖先

2019年8月19日22:33:35 评论 23

1.简介

Java 怎么获取事件对象的窗口祖先?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


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 = "tah1986.com";
        System.out.println(getWindowAncestor(eventSrc));
    }

    
    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);
        }
    }
}

 

3.总结

示例代码演示了 Java 怎么获取事件对象的窗口祖先,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: