将JMenuItem的名称赋予其ActionListener [英] Giving JMenuItem's name to it's ActionListener
问题描述
如何给我的 JMenuItem
名称附加的 ActionListener
看看?
How can I give my JMenuItem
s names that the ActionListener
attached to them will look at?
我有一个菜单系统由一个 ActionListener
处理,这些菜单中的一些项目重复名称。这不是用户端的问题,因为它显然是做什么的;事实上,如果他们有不同的名字会更令人困惑。但是,在我的结尾,我想要唯一地标记每个项目。
I've got a menu system that's handled by a single ActionListener
, and some items in those menus duplicate names. This isn't a problem on the user end, because it's obvious what does what; in fact, it would be more confusing if they had different names. However, at my end, I want to label each item uniquely.
创建我的项目的部分如下所示:
The section that creates my items looks like this:
String label = getLabel(forThisItem);
JMenuItem item = new JMenuItem(label);
item.setName(parentMenu.getName() + "_" + label);
item.addActionListener(actionListener);
parentmenu.add(item);
使用getName()在事后询问项目(在此方法的范围之外),给出名称I给它,因为它应该,但输出
Interrogating the item afterwards (and outside the scope of this method) with getName() gives the name I gave it, as it should, but the output of
public void actionPerformed(ActionEvent ae) {
String actionPerformed = ae.getActionCommand();
System.out.println("actionPerformed: " + actionPerformed);
}
是用户看到的可能重复的名称,由 label
,而不是我给它的唯一名称。
is the the, possibly duplicated, name that the user sees, specified by label
, not the unique name that I gave it.
如何向ActionListener提供正确的信息?
How can I give the right information to the ActionListener?
推荐答案
为什么不在menuitem上调用 setActionCommand
。而不是使用 setName
,如果你调用 setActionCommand
,你应该得到你在调用 getActionCommand
Why aren't you calling setActionCommand
on the menuitem. Instead of using setName
, if you call setActionCommand
, you should get what you expect when you call getActionCommand
此外,它的标签,而不是标签。
这篇关于将JMenuItem的名称赋予其ActionListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!