简体   繁体   中英

multiple JButton actionlistener from another class

hi everyone i have a problem on how to create a separate class of actionlistener this is my code right now which works fine but doesn't fill my needs.

for (int x = 0; x < buttons.length; x++) {
    buttons[x] = new JButton(name[x]);
    buttons[x].addActionListener(this);

}
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == buttons[0]) {
        //command
    } else if (e.getSource() == buttons[1]) {
        //command
    }  

}

So basically i want these buttons to have an action listener from another class.

Again, your question is a bit vague, a bit lacking in context. You already know that you can use any class that implements ActionListener as your button's ActionListener or any class that implements Action (or extends AbstractAction) as your button's Action, and it's easy to demonstrate this:

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

public class ActionExample extends JPanel {
   public static final String[] DAYS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};

   public ActionExample() {
      for (String day : DAYS) {
         add(new JButton(new MyAction(day)));
      }
   }

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

      JFrame frame = new JFrame("ActionExample");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_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();
         }
      });
   }
}

class MyAction extends AbstractAction {
   public MyAction(String name) {
      super(name);
   }

   @Override
   public void actionPerformed(ActionEvent evt) {
      System.out.println("Button pressed: " + evt.getActionCommand());
   }
}

But I fear that this still doesn't answer whatever problem you're having that we don't fully understand yet. If this answer, which shows how to use an outside class as an Action (which functions as an ActionListener), doesn't answer your question, then again, please provide more context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM