开发者

I have an instance of JMenuItem (let's say, TEMP). I want to find out, what is the name of JMenu to which a TEMP is added. How?

I have an instance of JMenuItem (let's say, T开发者_Go百科EMP). I want to find out, what is the name of JMenu to which a TEMP is added. How should I do it?


You can try the following code to get JMenu of given JMenuItem

JPopupMenu fromParent = (JPopupMenu)menuitem.getParent();  
JMenu foo = (JMenu)fromParent.getInvoker();  
System.out.println(foo.getName());  


You may get the JMenu's name from JMenuItem using this approach:

JPopupMenu popup = new JPopupMenu();
popup.setName("popup");
JMenu jMenu= new JMenu("menu");
jMenu.setName("menu");
JMenuItem menuItem1 = new JMenuItem("sub1");
jMenu.add(menuItem1);
menuItem1.addActionListener(this);
popup.add(jMenu);

....

@Override
public void actionPerformed(ActionEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    try{
        JMenuItem menuItem = (JMenuItem) e.getSource(); 
        JPopupMenu popupMenu = (JPopupMenu) menuItem.getParent(); 
        Component invoker = popupMenu.getInvoker();  
        // Print name of JMenu
        System.out.println("NAME OF JMENU: "+invoker.getName());    
        JPopupMenu popup = (JPopupMenu) invoker.getParent();
        // Print name of JPopupMenu
        System.out.println("NAME OF POPMENU: "+popup.getName());
    }catch(Exception ex){
        ex.printStackTrace();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜