如何确定哪个菜单项称为 ActionListener?
我有一个 Java 程序,其中有一个包含任意数量项目的 JMenu(在本例中,当前在不同程序中加载的每个动态库都有一个菜单项)。 我正在运行一个循环将 JCheckBoxMenuItem 添加到菜单中,因为我不知道会有多少个。
如何为这些菜单项设置一个动作侦听器,以了解哪个选项调用了它? 具体来说,我想运行相同的函数,但对每个菜单项使用不同的设置或参数(并且再次使用不同的函数,具体取决于检查是否被切换或解除切换)。
有人能指出我正确的方向吗?
I have a Java program where I have a JMenu with an arbitrary number of items (in this case, there is one menu item for each dynamic library currently loaded in a different program). I'm running a loop to add JCheckBoxMenuItem s to the menu, since I don't know how many there will be.
How can I set up an action listener for these menu items that is aware of which option called it? Specifically, I want to run the same function but with a different set or parameters for each of the menu items (and a different function again depending on whether the check is being toggled or detoggled).
Could someone point me in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
虽然 event.getSource() 肯定会让您知道事件来自哪个特定按钮,但它具有需要跟踪生成的按钮或窥探按钮的副作用。 此外,您可能希望向用户提供与用于标识库不同的库名称(可能包括版本信息)。 使用按钮的“ActionCommand”属性可以提供一种分离这些问题的方法。 因此,您需要更改生成复选框菜单项和侦听器中的代码。
操作处理程序代码将是...
While event.getSource() will definitely let you know which particular button the event came from it has the side effect of needing to track the generated buttons or snooping into the button. Also you may want to present a different name of the library to the user (possibly including the version information) than is used to identify the library. Using the "ActionCommand" property of the button may provide a way to separate those issues. So you will need to alter code in the generation of the checkbox menu items and in the listener.
The action handler code would be...
一定要仔细阅读:http://java.sun.com /docs/books/tutorial/uiswing/misc/action.html
简而言之,将 ActionListener 添加到 menuItems 中。 在actionPerformed方法中,使用event.getSource()。 如果需要,您可以将相同的 ActionListener 添加到所有菜单项。
Definitely read over this: http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html
In short, add ActionListener to the menuItems. In the actionPerformed method, use event.getSource(). You can add the SAME ActionListener to all your menu items if you want.
event.getSource() 应该做到这一点。
event.getSource() should do it.
当您构建菜单时,您可以将
Action
对象传递给JCheckBoxMenuItem
,该对象配置有给定操作所需的任何选项(您也可以将对复选框的引用推送到此处)检查状态)。 这样,当实际执行操作时,您将不必进行任何类型的处理,因为将调用正确的操作。When you build the menu you can pass the
Action
object to theJCheckBoxMenuItem
configured with whatever options you need for given action (you can also push there the reference to the check box to check the state). This way you will not have to do any kind of processing when the action is actually performed, because the correct action will be invoked.最简洁的方法是为每个创建一个不同的 ActionListener。
EventObject.getSource
很糟糕。The clean way to do it is to create a different
ActionListener
for each.EventObject.getSource
is fugly.