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.