how to get the name of a JMenu when a JMenuItem is clicked

依然范特西╮ 提交于 2019-12-10 11:45:34

问题


How would one get the name of the JMenu holding a clicked JMenuItem? I tried doing this:

public void actionPerformed(ActionEvent arg0) {
    JMenu menuthing = (JMenu)(arg0.getSource());
    String menuString =  menuthing.getText();
    JMenuItem source = (JMenuItem)(arg0.getSource());
    String colorType = source.getText();

But it gives me this error:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JMenuItem cannot be cast to javax.swing.JMenu

So is there a way to cast to JMenu, or some other way to determine the name? Thanks.


回答1:


I would suggest adding a MenuListener to your JMenu and add your code in public void menuSelected(javax.swing.event.MenuEvent evt).

Since this is a MenuEvent, the getSource() method will return the JMenu object

If you want to get it from your ActionEvent, try something like this:

JPopupMenu menu = (JPopupMenu) ((JMenuItem) evt.getSource()).getParent();
JMenu actMenu = menu.getInvoker();



回答2:


Instead of casting to a JMenu just cast to JMenuItem. Then get the JMenu from it.

JMenuItem jmi = (JMenuItem) arg0.getSource();
JPopupMenu jpm = (JPopupMenu) jmi.getParent();
JMenu menu = (JMenu) jpm.getInvoker();



回答3:


Assuming the JMenuItems are the children of JMenu, you may still do it with 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();
    }
}


来源:https://stackoverflow.com/questions/11979763/how-to-get-the-name-of-a-jmenu-when-a-jmenuitem-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!