【问题标题】:multiple JButton actionlistener from another class来自另一个类的多个 JButton actionlistener
【发布时间】:2014-12-21 18:21:15
【问题描述】:

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

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
    }  

}

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

【问题讨论】:

标签: java swing jbutton actionlistener


【解决方案1】:

同样,您的问题有点含糊,有点缺乏上下文。您已经知道可以使用任何实现 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),但不能回答您的问题,请再次提供更多上下文。

【讨论】:

    猜你喜欢
    • 2012-11-27
    • 1970-01-01
    • 2013-10-06
    • 2012-12-26
    • 2015-05-09
    • 2021-02-08
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    相关资源
    最近更新 更多