I would like to get the name of the JMenu when I click on my JMenuItem with a JPopupMenu.
I put an ActionListener named "menuContextuelListener" on each JMenuItem:
ActionListener menuContextuelListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println(event.getActionCommand());
}
};
How can I get the name of the JMenu parent from JMenuItem selected?
I also tried this way in the same listener, but it doesn't work :
JMenuItem jmi = (JMenuItem) event.getSource();
JPopupMenu jpm = (JPopupMenu) jmi.getParent();
JMenu menu = (JMenu) jpm.getInvoker();
And this one from how to get the name of a JMenu when a JMenuItem is clicked:
JPopupMenu menu = (JPopupMenu) ((JMenuItem) evt.getSource()).getParent();
JMenu actMenu = menu.getInvoker();
Full code of the listener :
ActionListener menuContextuelListener = new ActionListener(){
public void actionPerformed(ActionEvent event)
{
JMenuItem source = (JMenuItem)(event.getSource());
try{
JMenuItem menuItem = (JMenuItem) event.getSource();
JPopupMenu popupMenu = (JPopupMenu) menuItem.getParent();
Component invoker = popupMenu.getInvoker();
JPopupMenu popup = (JPopupMenu) invoker.getParent();
System.out.println("NAME OF JMENU: "+popup.getName());
}catch(Exception ex){
ex.printStackTrace();
}
}
};
Here an example of the construction of the menu (dynamically) :
tJMenu.add(new JMenu(ligne.substring(0, pos-1)));
tJMenu.get(tJMenu.size()-1).setName(ligne.substring(0, pos-1));
and I check with the code below... and I can see the names of the JMenu :
System.out.println(tJMenu.get(tJMenu.size()-1).getName());