我可以在一个类中使用多个ActionListener吗? [英] Can I use multiple ActionListeners in a single class?

查看:184
本文介绍了我可以在一个类中使用多个ActionListener吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面过于简化的例子;其中一些用伪代码编写,以简洁起见。当我尝试按原样运行时,我收到编译器错误,指出已在我的 main 方法中找到 actionPerformed 。但是,如果我重命名它,请说 actionPerformed2 它不再被 ActionListener 识别。

Consider the overly simplified example below; some of it written with pseudocode for brevity. When I try running this as is, I get a compiler error stating the actionPerformed is already found in my main method. However, if I rename it, say to actionPerformed2 it's no longer recognized by ActionListener.

我是否需要组合 foo foo2 方法分为单个 ActionListener 方法??在具有多个按钮对象的单个类中使用多个侦听器时,如何正确区分侦听器?

Do I need to combine the listeners for both the foo and foo2 methods into a single ActionListener method?? How do I properly differentiate listeners from each other when using multiple listeners in a single class with multiple button object?

我刚刚开始使用摇摆组件,所以我怀疑我可能不会问正确的问题......但我可以随时编辑。 :)

I'm just beginning to play with swing components, so I suspect I may not be asking the right questions...but I can always edit as I go. :)

public class foo  {
    declare button1, button2, button3 and panel1
    public foo()  { 
        show panel1 with button1 and button2;
    }
    public foo2() {
        show panel1 with button3;
    }
    public void actionPerformed(ActionEvent e)  { 
        Object source1 = e.getSource();
        do some stuff when button1 is clicked
    }
    public void actionPerformed(ActionEvent f)  {
        Object source2 = f.getSource();
        do some other stuff when button2 is clicked
    }
    public static void main(String[] args)   {
        foo myFoo = new foo();
    }
}


推荐答案

使用匿名的内部类。

例如,你永远不会写但代表一点的代码:

For example, code that you would never write but that illustrates a point:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Foo  extends JPanel {
   private JButton btnA = new JButton("Button A");
   private JButton btnB = new JButton("Button B");
   private JButton btnC = new JButton("Button C");

   public Foo() {
      btnA.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            System.out.println("button A Action");
         }
      });
      btnB.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            System.out.println("button B Action");
         }
      });
      btnC.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            System.out.println("button C Action");
         }
      });

      add(btnA);
      add(btnB);
      add(btnC);
   }

   private static void createAndShowGui() {
      Foo mainPanel = new Foo();

      JFrame frame = new JFrame("Foo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

我自己,我正在使用更多的AbstractActions和更少的ActionListeners ,甚至开始使用Command Design Pattern与PropertyChangeListener一起使用。

Myself, I'm using more AbstractActions and less ActionListeners, and have even started using the Command Design Pattern for this in concert with a PropertyChangeListener.

例如,我最新的GUI的视图部分如下所示:

As an example, my latest GUI's "view" section looks like this:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;

@SuppressWarnings("serial")
public class View {
   enum TextAreaDestination {
      EGD_IMPRESSION("EGD Impression"),
      EGD_RECOMMENDATIONS("EGD Recommendations"),
      COLON_IMPRESSION("Colon Impression"),
      COLON_RECOMMENDATIONS("Colon Recommendations"),
      ERROR_MESSAGES("Error Messages");

      private String text;
      private TextAreaDestination(String text) {
         this.text = text;
      }

      public String getText() {
         return text;
      }

      @Override
      public String toString() {
         return text;
      }
   }

   public enum GuiButtonText {
      GET_ONE_PROC("Get One Proc", KeyEvent.VK_O),
      GET_TWO_PROCs("Get Two Procs", KeyEvent.VK_T), 
      INTO_FLOW("Into Flow", KeyEvent.VK_F),
      CLEAR_ALL("Clear All", KeyEvent.VK_C),
      F_U_PROC_FLAG("F/U Proc Flag", KeyEvent.VK_U),
      SIGN_NEXT("Sign/Next", KeyEvent.VK_S),
      EXIT("Exit", KeyEvent.VK_X);
      private String text;
      private int mnemonic;
      private GuiButtonText(String text, int mnemonic) {
         this.text = text;
         this.mnemonic = mnemonic;
      }
      public String getText() {
         return text;
      }
      public int getMnemonic() {
         return mnemonic;
      }
   }

   public static final String BUTTON_PRESSED = "Button Pressed";

   private static final int TA_ROWS = 4;
   private static final int TA_COLS = 50;
   private JPanel mainPanel = new JPanel();
   private SwingPropertyChangeSupport spcSupport = new SwingPropertyChangeSupport(
         this);
   private Map<TextAreaDestination, JTextArea> impressionRecMap = new HashMap<TextAreaDestination, JTextArea>();

   public View() {
      JPanel textAreasPanel = createTextAreasPanel();
      JPanel buttonsPanel = createButtonsPanel();

      mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
      mainPanel.setLayout(new BorderLayout(5, 5));
      mainPanel.add(textAreasPanel, BorderLayout.CENTER);
      mainPanel.add(buttonsPanel, BorderLayout.PAGE_END);
   }

   private JPanel createButtonsPanel() {
      JPanel buttonsPanel = new JPanel(new GridLayout(2, 0, 5, 5));
      for (final GuiButtonText guiBtnText : GuiButtonText.values()) {
         AbstractAction btnAction = new AbstractAction(guiBtnText.getText()) {
            {putValue(MNEMONIC_KEY, guiBtnText.getMnemonic()); }
            @Override
            public void actionPerformed(ActionEvent e) {
               spcSupport.firePropertyChange(BUTTON_PRESSED, null, guiBtnText);               
            }
         };
         JButton button = new JButton(btnAction);
         buttonsPanel.add(button);
      }
      return buttonsPanel;
   }

   private JPanel createTextAreasPanel() {
      JPanel textAreasPanel = new JPanel();
      textAreasPanel.setLayout(new BoxLayout(textAreasPanel,
            BoxLayout.PAGE_AXIS));
      for (TextAreaDestination textDest : TextAreaDestination.values()) {
         JTextArea tArea = new JTextArea(TA_ROWS, TA_COLS);
         tArea.setName(textDest.getText());
         tArea.setWrapStyleWord(true);
         tArea.setLineWrap(true);
         impressionRecMap.put(textDest, tArea);
         JScrollPane scrollPane = new JScrollPane(tArea);
         JPanel outerPanel = new JPanel(new BorderLayout());
         outerPanel.setBorder(BorderFactory.createTitledBorder(textDest.getText()));
         outerPanel.add(scrollPane);
         textAreasPanel.add(outerPanel);
      }
      return textAreasPanel;
   }

   public String textAreasGetText(TextAreaDestination key) {
      JTextArea textArea = impressionRecMap.get(key);
      if (textArea != null) {
         return textArea.getText();
      } else {
         return ""; // throw exception
      }
   }

   public void textAreasSetText(TextAreaDestination key, String text) {
      JTextArea textArea = impressionRecMap.get(key);
      if (textArea != null) {
         textArea.setText(text);
      } else {
         // throw exception?
      }
   }

   public void textAreaAppend(TextAreaDestination key, String text) {
      JTextArea textArea = impressionRecMap.get(key);
      textArea.append(text);
   }

   public void clearAllAreas() {
      for (TextAreaDestination taDest : TextAreaDestination.values()) {
         textAreasSetText(taDest, "");
      }
   }

   public void addPropertyChangeListener(PropertyChangeListener listener) {
      spcSupport.addPropertyChangeListener(listener);
   }

   public void removePropertyChangeListener(PropertyChangeListener listener) {
      spcSupport.removePropertyChangeListener(listener);
   }

   public JPanel getMainPanel() {
      return mainPanel;
   }

   public static void main(String[] args) {
      Control.main(args);
   }
}

控制部分的一部分看起来像所以:

And a portion of the "control" section looks like so:

import java.awt.Component;
import java.awt.Window;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
import procedure.findings4.View.TextAreaDestination;

public class Control {
   public static final boolean DEBUG = false;

   public static final String CENTRICITY_WINDOW_NAME = "Centricity EMR";
   private DriverModel driverModel = null;
   private View view;
   private Map<View.GuiButtonText, Runnable> runnableMap = new HashMap<View.GuiButtonText, Runnable>();

   public Control() {
      runnableMap.put(View.GuiButtonText.GET_ONE_PROC, new GetOneProcRunnable());
      runnableMap.put(View.GuiButtonText.GET_TWO_PROCs,
            new GetTwoProcsRunnable());
      runnableMap.put(View.GuiButtonText.INTO_FLOW, new IntoFlowRunnable());
      runnableMap.put(View.GuiButtonText.CLEAR_ALL, new ClearAllRunnable());
      runnableMap.put(View.GuiButtonText.SIGN_NEXT, new SignNextRunnable());
      runnableMap.put(View.GuiButtonText.EXIT, new ExitRunnable());
   }

   public void setView(View view) {
      this.view = view;
      view.addPropertyChangeListener(new ViewChangeListener());
   }

   //....

   private class ViewChangeListener implements PropertyChangeListener {
      @Override
      public void propertyChange(PropertyChangeEvent pcEvt) {
         if (pcEvt.getPropertyName().equals(View.BUTTON_PRESSED)) {
            Runnable run = runnableMap.get(pcEvt.getNewValue());
            if (run != null) {
               run.run();
            }
         }
      }
   }

   //....

请注意,我并不认为自己是这方面的专家,但我只是尽力管理复杂性。可能有更好的方法给这只猫上皮。

Note that I don't claim to be an expert at this, but am only trying to manage complexity as best I can. There are probably better ways to skin this cat.

这篇关于我可以在一个类中使用多个ActionListener吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆