【问题标题】:How can I determine which menu item called an ActionListener?如何确定哪个菜单项称为 ActionListener?
【发布时间】:2009-02-26 00:49:47
【问题描述】:

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

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

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

【问题讨论】:

    标签: java swing events menu menuitem


    【解决方案1】:

    虽然 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...
    }
    

    【讨论】:

      【解决方案2】:

      请务必阅读:http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html

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

      【讨论】:

        【解决方案3】:

        event.getSource() 应该这样做。

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            【解决方案5】:

            干净的方法是为每个人创建一个不同的ActionListenerEventObject.getSource 很丑。

            【讨论】:

            • 当然可以,但是我将如何使用编译时未知的参数调用每个 ActionListener?
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-06-05
            • 2015-05-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多