1

I am trying to find of way of selecting an element in a JMenu by name. Basically, what I want to do is this:

public boolean setEnableByName(boolean enable, String itemName) {
   for (Component item :  myJMenu.getComponents()) {
      if (item.getName().equals(itemName)) {
          item.setEnabled(enable);
          return true;
      }
   }
   return false;
}

I have tried iterating on myJMenu.getComponents() or myJMenu.getMenuComponents(), to no avail. I've searched for the reason and it seems to be caused by the JMenu not stocking directly the submenus and items directly, i.e they're not really present.

There is a similar question on SO, but it dates from 2012, and swing had a lot of changes.

I tested with a JMenu containing 2 JMenus and 2 JMenuItems. The results I got:

  • While using getComponents(): I never enter the foreach (aka there are no elements returned)
  • While using getMenuComponents(): I get the two JMenu elements

NOTE: Note that I can't use this method as the elements triggering the action can be anywhere in the code.

NOTE: From the tests, I found out that, for my menu, getComponentsCount returned 0, getMenuComponentsCount returned 4, just like getItemsCount. My problem came from the fact that I was comparing the name and not the text of my elements.

Community
  • 1
  • 1
Turtle
  • 1,626
  • 16
  • 26

1 Answers1

2

I assume you are looking for JMenuItems and also that you added them to your JMenu using add function. In that case you could use the getItemCount() and getItem(int pos) functions as below:

public boolean setEnableByName(boolean enable, String itemName) {
   for (int i = 0 ; i <  myJMenu.getItemCount(); i++) {
      JMenuItem item = myJMenu.getItem(i);
      if (item.getName().equals(itemName)) {
          item.setEnabled(enable);
          return true;
      }
   }
   return false;
}
SomeDude
  • 13,876
  • 5
  • 21
  • 44