如何获得持有点击的JMenuItem的JMenu的名称?我试过这样做:
public void actionPerformed(ActionEvent arg0) {
JMenu menuthing = (JMenu)(arg0.getSource());
String menuString = menuthing.getText();
JMenuItem source = (JMenuItem)(arg0.getSource());
String colorType = source.getText();
但它给了我这个错误:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JMenuItem cannot be cast to javax.swing.JMenu
那么有没有办法投射到JMenu,或者其他一些方法来确定名称? 感谢。
答案 0 :(得分:3)
我建议您在MenuListener
添加JMenu
,并在public void menuSelected(javax.swing.event.MenuEvent evt)
中添加您的代码。
由于这是MenuEvent
,getSource()
方法将返回JMenu
对象
如果您想从ActionEvent
获取,请尝试以下操作:
JPopupMenu menu = (JPopupMenu) ((JMenuItem) evt.getSource()).getParent();
JMenu actMenu = menu.getInvoker();
答案 1 :(得分:2)
而不是强制转换为JMenu只是强制转换为JMenuItem。然后从中获取JMenu。
JMenuItem jmi = (JMenuItem) arg0.getSource();
JPopupMenu jpm = (JPopupMenu) jmi.getParent();
JMenu menu = (JMenu) jpm.getInvoker();
答案 2 :(得分:0)
假设JMenuItems是JMenu的子代,你仍然可以使用ActionEvent:
JPopupMenupopup = new JPopupMenu();
popup.setName("popup");
...
@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();
JPopupMenu popup = (JPopupMenu) invoker.getParent();
System.out.println("NAME OF JMENU: "+popup.getName());
//If you need the selection of cell(s)
JTable table = (JTable)popup.getInvoker();
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
System.out.println("Selected cell: "+row+"-"+col);
}catch(Exception ex){
ex.printStackTrace();
}
}