繁体   English   中英

来自另一个类的多个JButton actionlistener

[英]multiple JButton actionlistener from another class

大家好,我对如何创建单独的动作侦听器类有疑问,现在这是我的代码,可以正常工作,但不能满足我的需求。

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
    }  

}

所以基本上我希望这些按钮具有另一个类的动作侦听器。

同样,您的问题有点含糊,缺乏上下文。 您已经知道可以将实现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());
   }
}

但是我担心这仍然无法解决您所遇到的任何问题,因为我们尚未完全理解。 如果此答案(说明如何将外部类用作Action(用作ActionListener))没有回答您的问题,请再次提供更多上下文。

暂无
暂无

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

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