title: Accessing JMenuItems from JMenuBarbar in Java?
body: <p>I'm working with some java code specifically on a menu bar right now and I'm having trouble accessing a menu item from a JMenuBar. The menu bar has an item JMenu, and the JMenu has a JMenuItem in it, I'm trying to access the JMenuItem, differentiating items by the name attribute (this is just one way I found to differentiate between them, if anybody knows a better way to do this please let me know.) I'm doing this on the on-change event in switching tabs in my application, so here is my code.</p>
  
  <pre><code>public void stateChanged(ChangeEvent e) {
      if(tabbedPane.getSelectedIndex() != 0){
          for(int i = 0; i &lt; menuItems.length; i++){
              MenuElement[] subItems = menuItems[i].getSubElements();
              for(int j = 0; j &lt; subItems.length; j++){
                      System.out.println(subItems[j].getComponent().getName());
              }
          }
      }
  }
  </code></pre>
  
  <p>The menuItems comes from a getSubElements() call on the JMenuBar, I can get the 'File' element, but when I do the second loop to find the item underneath 'File' most of the attributes including name are null, even though I set name already.</p>
  
  <p>In the debugger I can see the name I set when doing a watch on subItems[j].getComponent(), under a section labeled 'component', then under 'element data[0]'.</p>
  
  <p>I'm sure there's a way to get to this attribute but I haven't been able to figure out how. Does anybody know how to access this or know a better way to distinguish between MenuItems from a JMenuBar?</p>
  
  <p>Thanks.</p>
  
  <p>EDIT - I figured it out. If anybody is curious the JMenuItem was nested within another layer in the JMenu. This code prints out the name I was trying to find.</p>
  
  <pre><code>public void stateChanged(ChangeEvent e) {
      if(tabbedPane.getSelectedIndex() != 0){
          for(int i = 0; i &lt; menuItems.length; i++){
              MenuElement[] subItems = menuItems[i].getSubElements();
              for(int j = 0; j &lt; subItems.length; j++){
                  MenuElement[] subSubItems = subItems[j].getSubElements();
                  for(int k = 0; k &lt; subSubItems.length; k++){
                      System.out.println(subSubItems[k].getComponent().getName());
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>That being said I have no idea why this is. Anybody know?
  Here is the code that builds the JMenuBar:</p>
  
  <pre><code>public void buildMenu(){
      menuBar = frame.getJMenuBar();
      menu = new JMenu("File");
      menu.setName("file");
      menuBar.add(menu);
      importTiles = buildImportTilesMenuItem();
      menu.add(importTiles);
  }
  
  public JMenuItem buildImportTilesMenuItem(){
      importTiles = new JMenuItem("Import Tiles");
      importTiles.setName("importTiles");
      importTiles.addActionListener(this);
      return importTiles;
  }
  </code></pre>