查找组合框弹出窗口的所有者

az31mfrm  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(260)

我有一个弹出的设置显示给用户。如果在它外面单击,它将隐藏,但如果在里面单击,它将保持可见。
处理此行为的事件处理程序将获取 Component (已单击)并使用 component.getParent() 我可以递归地检查它是否是我的设置面板的子级。到目前为止,这已经奏效了。
但我只是加了一个 JComboBox 结果显示,当单击时显示的组合框“可选项目弹出窗口”(是否有名称?)不是组合框的子项。尝试在组合框中选择某个内容将隐藏“我的设置”面板。
使用netbeans调试器,我可以看到它的类型 BasicComboPopup$1 (这是一个匿名类吗?),但它不是这两个类的示例 ComboPopup , JPopupMenu 也不是 BasicComboPopup .
我需要一种方法来确定所有者/父组合框的“组合框弹出”被点击。

1zmg4dgp

1zmg4dgp1#

不知道你是不是在说 mouse 事件 keyboard 事件 mouse 以及 keyboard 事件
看看你的勇气有什么方法 child v、 s。 parent 反之亦然
发布一个sscce,详细描述所需的事件,因为有几种方法可以扩展和修改 PopupJComboBox 编辑
如果你使用 AWT Popup 或混合 Swing lightweightAWT heavyweight 组件,然后你必须看看darryl的swing utils

mnowg1ta

mnowg1ta2#

不完全确定,但你可能在找

popup.getInvoker();

它将返回调用组合框。
下面的实用方法(从swingx框架附带的swingxutilities复制):假设您找到了源组件(不幸的是,方法中的命名是focusowner;-)对于事件,它检查该源是否在父级下面的某个位置,包括弹出窗口。
只是注意到你的父级是一个弹出窗口,所以你必须稍微调整一下逻辑,切换第一个和第二个if块(尽管没有尝试,但有多个可见的弹出窗口是不寻常的。)

/**
 * Returns whether the component is part of the parent's
 * container hierarchy. If a parent in the chain is of type 
 * JPopupMenu, the parent chain of its invoker is walked.
 * 
 * @param focusOwner
 * @param parent
 * @return true if the component is contained under the parent's 
 *    hierarchy, coping with JPopupMenus.
 */
public static boolean isDescendingFrom(Component focusOwner, Component parent) {
    while (focusOwner !=  null) {
        if (focusOwner instanceof JPopupMenu) {
            focusOwner = ((JPopupMenu) focusOwner).getInvoker();
            if (focusOwner == null) {
                return false;
            }
        }
        if (focusOwner == parent) {
            return true;
        }
        focusOwner = focusOwner.getParent();
    }
    return false;
}

相关问题