How do I get the index of a JMenuItem in a JMenu?

I need to find the index of a particular JMenuItem

in JMenu

so that I can programmatically insert()

add a new one JMenuItem

right before it. How can i do this?

+3


source to share


3 answers


Use Container#getComponentZOrder(Component)

which should return the index position of the component in the container



+2


source


Here is some sample code for the same solution as suggested above:

JPopupMenu popup = new JPopupMenu();
popup.setName("popup");
JMenu jMenu= new JMenu("menu");
jMenu.setName("menu");
JMenuItem menuItem1 = new JMenuItem("sub1");
jMenu.add(menuItem1);
menuItem1.addActionListener(this);
popup.add(jMenu);

      



....

@Override
public void actionPerformed(ActionEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    try{
        JMenuItem menuItem = (JMenuItem) e.getSource(); 
        JPopupMenu popupMenu = (JPopupMenu) menuItem.getParent(); 
        Component invoker = popupMenu.getInvoker();  
        // Print MenuItem index against the total number of items
        System.out.println(popupMenu.getComponentZOrder(menuItem)+"/"+popupMenu.getComponentCount());
    }catch(Exception ex){
        ex.printStackTrace();
    }
}

      

+1


source


In the JMenuItem action listener, get the source and do something like this.

for(int i = 0; i < jmenu.getMenuComponents().length; i++){
     if(jMenu.getMenuComponent(i) == jMenuItem ){
              // so that i is index here...
     }
}

      

here jMenuItem is e.getSource()

0


source







All Articles