本文介绍了如何实现和保存多个actionListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我有一个包含多个Menu和MenuItem的类(我们称之为:MenuBarClass)。
我想给每个MenuItem分配一个actionlistener,但是......而不是做类似的事情:

Ok, I have one class (let's call it: MenuBarClass) that contain multiple Menu and MenuItem.I whant assign to every MenuItem an actionlistener, but.. instead of doing something like:

menuitem_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {} });
menuitem_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {} });
menuitem_3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {} });
// ...
menuitem_N.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {} });

我认为我的代码更具可持续性......更重要的是......我没有大量的if在一个巨大的ActionListener类中如下:

I whant my code more mantainable and.. more important.. I don't whant a lots of "if" in one huge ActionListener class like:

public void actionPerformed(ActionEvent e) {
  if (e.getSource().equals(menuitem_1)) {
    //do stuff..
  } else if (e.getSource().equals(menuitem_2)) {
    //do stuff..
  } else ...
}

我怎么能这样做,如果有可能的?
任何人都可以帮忙吗?

how can i do this, if it is possible?Can anyone help?

推荐答案

您可以使用用于创建实用程序方法的API:

You can reduce verbosity using the reflection API to create a utility method:

package demo;    
import java.awt.event.*;
import java.lang.reflect.*;

public class ListenerProxies {    
  private static final Class<?>[] INTERFACES = { ActionListener.class };

  public static ActionListener actionListener(final Object target,
                                                    String method) {
    final Method proxied = method(target, method);
    InvocationHandler handler = new InvocationHandler() {
      @Override
      public Object invoke(Object proxy, Method method, Object[] args)
          throws Throwable {
        ActionEvent event = (ActionEvent) args[0];
        return proxied.invoke(target, event);
      }
    };
    return (ActionListener) Proxy.newProxyInstance(target.getClass()
        .getClassLoader(), INTERFACES, handler);
  }

  private static Method method(Object target, String method) {
    try {
      return target.getClass().getMethod(method, ActionEvent.class);
    } catch (NoSuchMethodException e) {
      throw new IllegalStateException(e);
    } catch (SecurityException e) {
      throw new IllegalStateException(e);
    }
  }
}

这可以像这样使用:

package demo;
import static demo.ListenerProxies.actionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class Demo {

  public static void main(String[] args) {
    Demo test = new Demo();
    JButton hello = new JButton("Say Hello");
    hello.addActionListener(actionListener(test, "sayHello"));
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(hello);
    frame.pack();
    frame.setVisible(true);
  }

  public void sayHello(ActionEvent event) {
    System.out.println("Hello");
  }
}

缺点是缺乏编译时间检查是否存在 sayHello(ActionEvent)方法。

The downside of this is the lack of compile-time checking that the sayHello(ActionEvent) method exists.

性能成本可以忽略不计。

The performance costs will be negligible.

这篇关于如何实现和保存多个actionListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 09:06