简体   繁体   English

来自另一个类的多个JButton actionlistener

[英]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: 您已经知道可以将实现ActionListener的任何类用作按钮的ActionListener,也可以将实现Action(或扩展AbstractAction)的任何类用作按钮的Action,这很容易演示:

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. 如果此答案(说明如何将外部类用作Action(用作ActionListener))没有回答您的问题,请再次提供更多上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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