问题
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