MenuListener实现,如何检测哪个JMenu被点击?
如果我像这样定义了 JMenu
和 JMenuBar
:
private JMenuBar jMenuBar;
private JMenu jMenu1;
jMenuBar = new JMenuBar();
jMenu1 = new JMenu();
jMenu1.setText("ABOUT");
//and here add a MenuListener so that i can detect when a menu is clicked:
jMenu1.addMenuListener(this);
jMenuBar.add(jMenu1);
setJMenuBar(jMenuBar);
//and here i implement the menulisteners
public void menuSelected(MenuEvent e) {
//my logic here
}
public void menuDeselected(MenuEvent e) {}
public void menuCanceled(MenuEvent e) {}
现在它工作正常。但问题是,如果我有多个菜单,我如何区分两者。 就像在菜单监听器中一样,我如何知道点击来自菜单 1 还是另一个菜单 2?
我的意思是,如果我有另一个菜单,并且我也为此菜单添加菜单侦听器:
jMenu2.addMenuListener(this);
那么我无法区分点击来自哪个菜单。我怎样才能做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用 getSource() 方法“nofollow">MenuEvent 类。或者,您也可以将单独的侦听器作为匿名类添加到两个菜单。
或
如果您选择第二个选项,则可以轻松使用(根据 @Kleopatra 在评论中的建议删除了此内容)ActionListener
而不是MenuListener
。 (仅当您不想对 menuCanceled 和 menuDeselected 进行操作时)You can use
getSource()
method of MenuEvent class. Or you can also add separate listeners to both menus as anonymous class.or
If you choose second option then it will easy to use(removed this as suggested by @Kleopatra in comment)ActionListener
instead ofMenuListener
. (Only if you do not want to do operation on menuCanceled and menuDeselected)这就是
getSource ()
是 for,它是MenuEvent
继承自EventObject
的方法。That is what
getSource()
is for, which is a methodMenuEvent
inherits fromEventObject
.您可以使用
ActionListener
来代替。以下是如何捕获对菜单项的单击如果您有多个菜单在单击时共享相同的代码,那么您可以将操作侦听器重构为一个单独的类。
You can use
ActionListener
instead. Here is how you can capture a click on a menu itemIf you have more than one menu sharing the same bit of code when clicked then you can refactor the action listener into a separate class.
我认为一种方法是将
ButtonModel
添加到JMenuItem
或将JMenuItems
添加到ButtonGroup
也可以轻松解决这个问题,例如 ButtonModelI think that one of ways is add
ButtonModel
toJMenuItem
or addJMenuItems
to theButtonGroup
can solve confortly that too, example for ButtonModel我来这里是为了看看是否有什么东西我更喜欢 getSource(),并决定坚持使用 getSource。我更喜欢使用字符串(而不是比较对象),因此我发布了我的代码,以防它对任何人有帮助。 (我知道有些人不喜欢提前返回,不喜欢 switch 语句,不喜欢 K&R。同样,个人喜好,根据需要进行调整。)
当然,JMenu 不使用 addMenuListener()甚至不触发menuSelected()。
I came here to see if there was anything I preferred to getSource(), and decided to stick with getSource. It's my preference to work with strings (vs comparing objects), so I'm posting my code in case it's helpful to anyone. (I know some people don't like early returns, don't like switch statements, don't like K&R. Again, personal preference, adapt as desired.)
Naturally, JMenu(s) that don't addMenuListener() don't even trigger menuSelected().
更改按钮或标签的颜色。简单而简短的xoxo
Change the colour of the button or label. simple and short xoxo