获取 JMenuItem 的窗口?

问题描述 投票:0回答:1

有没有办法获取

JMenuItem
所属的窗口?我尝试了这个概念验证:

JFrame testFrame = new JFrame();
testFrame.setSize(300, 100);
testFrame.setLocationRelativeTo(null);

JMenuBar testBar = new JMenuBar();
JMenu testMenu = new JMenu("Test");
JMenuItem testItem = new JMenuItem("Parent Test");

testItem.addActionListener(e -> {
    System.out.println("Has Top Level Ancestor: " + (testItem.getTopLevelAncestor() != null));
    System.out.println("Has Window Ancestor: " + (SwingUtilities.getWindowAncestor(testItem) != null));
});

testBar.add(testMenu);
testMenu.add(testItem);

testFrame.setJMenuBar(testBar);
testFrame.setVisible(true);

输出是:

Has Top Level Ancestor: false
Has Window Ancestor: false
java swing parent jmenuitem
1个回答
0
投票

我将其更改为打印菜单项的父级:

testItem.addActionListener(e -> System.out.println(testItem.getParent().getClass().getSimpleName()));

它打印“JPopupMenu”而不是“JMenu”,这意味着

testMenu
不是
testMenuItem
的父级。但是,如果您转换父类并调用
JPopupMenu#getInvoker
,它将返回 JMenu。

考虑到这一点,我创建了以下方法:

private static Window getWindowAncestor(JMenuItem item) {
    Container parent = item.getParent();
    if (parent instanceof JPopupMenu)
        return SwingUtilities.getWindowAncestor(((JPopupMenu) parent).getInvoker());
    else if (parent instanceof Window)
        return (Window) parent;
    else
        return SwingUtilities.getWindowAncestor(parent);
}

有效:)

© www.soinside.com 2019 - 2024. All rights reserved.