3

I need to find the index of a specific JMenuItem in a JMenu so I can programatically insert() a new JMenuItem right before it. How can I go about doing that?

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131
  • Have you tried Container#getComponentZOrder(Component)? – MadProgrammer Sep 15 '14 at 21:21
  • @MadProgrammer guess you forgot adding link, here it is: [Container#getComponentZOrder(Component)](http://docs.oracle.com/javase/7/docs/api/java/awt/Container.html#getComponentZOrder%28java.awt.Component%29) – Frakcool Sep 15 '14 at 21:40
  • 1
    @Frakcool Nah, I'm on the iPad and it's just a pain...:P – MadProgrammer Sep 15 '14 at 22:07
  • @MadProgrammer Make it an answer if you want :) BTW: is there a reason people write `Class#method` instead of `Class.method`? Is it some kind of convention? – Aviv Cohn Sep 17 '14 at 12:41
  • I use Class#method to indicate a instance method! where as Class.method indicates a static method – MadProgrammer Sep 17 '14 at 21:04

3 Answers3

2

Use Container#getComponentZOrder(Component) which should return the index position of the component within the container

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

Here's a code sample of 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();
    }
}
George
  • 6,006
  • 6
  • 48
  • 68
0

In 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()

subash
  • 3,116
  • 3
  • 18
  • 22