Reputation: 17203
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?
Upvotes: 3
Views: 3103
Reputation: 6084
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();
}
}
Upvotes: 1
Reputation: 347234
Use Container#getComponentZOrder(Component)
which should return the index position of the component within the container
Upvotes: 2
Reputation: 3140
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()
Upvotes: 0