簡體   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