我可以在一个类中使用多个ActionListener吗?

时间:2012-05-06 16:54:40

标签: java swing awt actionlistener

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

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

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

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();
    }
}

1 个答案:

答案 0 :(得分:10)

为此使用匿名内部类。

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

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一起使用。

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

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);
   }
}

“控制”部分的一部分看起来像这样:

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();
            }
         }
      }
   }

   //....

请注意,我并不是自称是专家,但我只是尽力管理复杂性。可能有更好的方法来抚育这只猫。