Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7921489
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T16:36:06+00:00 2026-06-03T16:36:06+00:00

Consider the overly simplified example below; some of it written with pseudocode for brevity.

  • 0

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.

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();
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T16:36:07+00:00Added an answer on June 3, 2026 at 4:36 pm

    Use anonymous inner classes for this.

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

    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.

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider this example: <% int testNumber = 1; %> //Some HTML goes here <%=testNumber%>
Consider this overly simple test: class foo { public: foo(int i); template< typename T
Consider this simplified model in Django: class Item(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField()
Consider this one piece of Perl code, $array[$x]->{foo}->[0]= January; I analyze this code as
Consider this url: www.anysite.com/get_count/?sex=5&sex=6&city=5&city=7&job=7&job=8...... For using in dynamic query in view: model = anyModel.objects.filter(sex=5).filter(sex=6).filter(city=5)....
Consider this JavaScript code snippet: Object.prototype.log = function() { // here, you have a
Consider the following text(csv) file: 1, Some text 2, More text 3, Text with
Consider a simple Enumerator like this: natural_numbers = Enumerator.new do |yielder| number = 1
Consider this title for a web page: This is a mixed text from right-to-left
Consider this code: int a = 5; if (a == 5 || a ==

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.