0

我有一个 Java 程序,其中有一个带有任意数量项目的 JMenu(在这种情况下,当前加载到不同程序中的每个动态库都有一个菜单项)。我正在运行一个循环来将 JCheckBoxMenuItem 添加到菜单中,因为我不知道会有多少。

如何为这些菜单项设置一个动作侦听器,以了解哪个选项调用它?具体来说,我想为每个菜单项运行相同的功能,但使用不同的设置或参数(以及根据检查是切换还是解除切换再次使用不同的功能)。

有人能指出我正确的方向吗?

4

5 回答 5

2

一定要仔细阅读:http: //java.sun.com/docs/books/tutorial/uiswing/misc/action.html

简而言之,将 ActionListener 添加到 menuItems 中。在 actionPerformed 方法中,使用 event.getSource()。如果需要,您可以将 SAME ActionListener 添加到所有菜单项。

于 2009-02-26T00:56:25.550 回答
2

虽然 event.getSource() 肯定会让您知道事件来自哪个特定按钮,但它具有需要跟踪生成的按钮或窥探按钮的副作用。此外,您可能希望向用户显示与用于标识库的名称不同的库名称(可能包括版本信息)。使用按钮的“ActionCommand”属性可以提供一种分离这些问题的方法。因此,您需要在生成复选框菜单项和侦听器中更改代码。

ActionListener actionListener = ... // whatever object holds the method, possibly this
String[] libraries = ... // however you get your library names
JMenu parentMenu = ... // the menu you are adding them to

for (String s : libraries) {
  // prettyName is a method to make a pretty name, perhaps trimming off
  // the leading path
  JCheckBoxMenuItem child = new JCheckBoxMenuItem(prettyName(s), true);
  child.setActionCommand(s);
  parentMenu.acc(child);
}

动作处理程序代码将是...

public void actionPerformed(ActionEvent evt) {
  // the 'current' selection state, i.e. what it is going to be after the event
  boolean selected = ((JCheckBoxMenuItem)evt.getSource()).isSelected();
  String library = evt.getActionCommand();
  ... process based on library and state here...
}
于 2009-02-26T03:11:52.730 回答
1

event.getSource() 应该这样做。

于 2009-02-26T00:54:18.940 回答
1

当您构建菜单时,您可以将Action对象传递给JCheckBoxMenuItem配置了您需要执行给定操作的任何选项(您也可以将对复选框的引用推到此处以检查状态)。这样,当实际执行操作时,您将不必进行任何类型的处理,因为将调用正确的操作。

于 2009-02-26T00:57:30.167 回答
0

干净的方法是ActionListener为每个创建一个不同的。EventObject.getSource丑陋的。

于 2009-02-26T12:29:03.653 回答