我有一个JMenuItem实例(比方说,TEMP)。我想知道,添加TEMP的JMenu的名称是什么。我该怎么办?
答案 0 :(得分:2)
您可以尝试以下代码来获取给定JMenuItem的JMenu
JPopupMenu fromParent = (JPopupMenu)menuitem.getParent();
JMenu foo = (JMenu)fromParent.getInvoker();
System.out.println(foo.getName());
答案 1 :(得分:0)
您可以使用以下方法从JMenuItem获取JMenu的名称:
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 name of JMenu
System.out.println("NAME OF JMENU: "+invoker.getName());
JPopupMenu popup = (JPopupMenu) invoker.getParent();
// Print name of JPopupMenu
System.out.println("NAME OF POPMENU: "+popup.getName());
}catch(Exception ex){
ex.printStackTrace();
}
}