单击JMenuItem时如何获取JMenu的名称 [英] how to get the name of a JMenu when a JMenuItem is clicked

查看:382
本文介绍了单击JMenuItem时如何获取JMenu的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得持有单击的JMenuItem的JMenu的名称?我尝试这样做:

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

但这给了我这个错误:

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

那么有没有一种方法可以转换为JMenu或其他确定名称的方法?
谢谢。

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

推荐答案

我建议添加 MenuListener JMenu 并将代码添加到 public void menuSelected(javax.swing.event.MenuEvent evt)中。

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

由于这是 MenuEvent ,因此 getSource()方法如果要从 ActionEvent中获取它,将返回 JMenu 对象

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

code>,尝试这样的事情:

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

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

这篇关于单击JMenuItem时如何获取JMenu的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆