Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Iterate a JMenu on its JMenuItems

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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;
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!