Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda