Jeeter
Jeeter

Reputation: 6085

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

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.

Upvotes: 1

Views: 6537

Answers (3)

George
George

Reputation: 6084

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();
    }
}

Upvotes: 0

Sujay
Sujay

Reputation: 6783

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();

Upvotes: 3

km1
km1

Reputation: 2443

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();

Upvotes: 2

Related Questions