javaswingjmenujpopupmenu

Accessing parent text from sub meny in Jmenu/JPopupmenu


I have structure that resembles a hashmap but in JMenu format. The main meny is not my code but i have added the JMenu "Manuellt resursbyte" to that menu. That menu have a few resources as a JmenuItem (not in bold) and a few JMenus (Bold).

Menu

What i want to do is when "P2" in this case is selected, also retrieve "S7".

The code for adding the menus look like this:

//Checks for this format: X,X;Y,Y

if(secResStr.contains(";")) {                                       
    String[] resSplit = secResStr.split(";");
                
                
    String firstResources = resSplit[0];
    String secondResources = resSplit[1];
                
    String[] firstSplitResources = firstResources.split(",");
    String[] secondSplitResources = secondResources.split(",");
                
    for (String firstRes : firstSplitResources) {
        JMenu switchMenu = new JMenu(firstRes);
                    
        for (String secondRes : secondSplitResources) {
            addStrToMenu(switchMenu, secondRes, true);
        }
        switchMenu.setFont(new JMenuItem(firstRes).getFont().deriveFont(Font.BOLD));
        menu.add(switchMenu);
    }
                
}

This addStrToMenu:

private void addStrToMenu(JMenu menu, String str, boolean bold) {
    JMenuItem resItem = new JMenuItem(str);

    if (bold) {
        resItem.setFont(resItem.getFont().deriveFont(Font.BOLD));
    }
    resItem.addActionListener(resourceListListener);
    menu.add(resItem);
}

When the actionListener is trigered i can retrieve the "P2" text but if i try to use getParent() on that i am forced to cast it to a JPopupMenu even though it was a jMenu that was added.

private void initListener() {
    resourceListListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JMenuItem source = (JMenuItem) e.getSource();
            String text = source.getText();
            
            System.out.println(text);
            
            JPopupMenu parent = (JPopupMenu) source.getParent();                                                    
        }
    };
}

The problem with JpopupMenu is that it doesn't have a "getText()" method so i have no way of accessing the menu text "SW".

Is there a way to to this or should i look for other alternatives?


Solution

  • Update in case anyone have the same issue. It turns out JMenus/JPopupMenus didn't work the way i figured. If you want to access the parent JMenu from the child you have to use the getInvoker() method on the parent to get to the JMenu.

    something like this worked for me:

     JMenu menu = null;
     JPopupMenu parentPopup = (JPopupMenu)item.getParent();
     item = (JMenuItem)parentPopup.getInvoker();
    
     if (! (item.getParent() instanceof JPopupMenu) ){
          menu = (JMenu)item;
     }
    

    And from there you can use the .getText() method!