Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda