将 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() 询问项目(并且在此方法的范围之外)给出了我给它的名称,正如它应该的那样,但是输出
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?
推荐答案
你为什么不在菜单项上调用 setActionCommand
.如果你调用 setActionCommand
,而不是使用 setName
,你应该在调用 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屋!