How do I get the index of a JMenuItem in a JMenu?
3 answers
Use Container#getComponentZOrder(Component)
which should return the index position of the component in the container
+2
source to share
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 to share