3
JPanel p = new JPanel();
    p.setLayout(new GridLayout(4, 4, 5, 5));
    String[] buttons = {
        "1", "2", "3", "/", "4",
        "5", "6", "*", "7", "8", "9", "-", "0", ".", "=", "+"
    };
    for (int i = 0; i < buttons.length; i++) {
            p.add(new JButton(buttons[i]));
   add(p);

这段代码产生了一个很好的计算器布局是否有一种方法可以将ActionListener 添加到每个按钮,同时保持这个布局我的意思是不要像这样对每个按钮都这样做。

JButton button1 = new JButton("1");
     button1.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent event) {
// interesting code for button1 goes here
      }
   });
4

4 回答 4

4

是的,而不是一个数组String,有一个Action实例数组。每个这样Action的都有一个名字,也是一个ActionListener. 这里引用了几个例子。

于 2012-11-04T12:28:07.743 回答
3

您可以简单地以 的形式向循环中的ActionListener每个按钮添加一个:forAbstractAction

for (int i = 0; i < buttons.length; i++) {
   JButton button = new JButton(buttons[i]);
   button.addActionListener(new MyAction());
   p.add(button);
}

在哪里

class MyAction extends AbstractAction {
   @Override
   public void actionPerformed(ActionEvent event) {
   ...
   }
}
于 2012-11-04T12:30:54.637 回答
2

根据我的经验,您可以创建按钮列表并循环运行以添加ActionListener

List<JButton> buttonsList = new ArrayList<JButton>(buttons.length):

for (JButton currButton : buttonsList) {

       currButton.addActionListener(){
         ....
       }
   ....
}
于 2012-11-04T12:29:50.250 回答
2

我用这段代码做到了...

   String[] buttons = {
        "1", "2", "3", "/", "4",
        "5", "6", "*", "7", "8", "9", "-", "0", ".", "=", "+"
    };

    Action[] allActions = new Action[buttons.length];

    for ( i = 0; i < buttons.length; i++) {

        allActions[i] = new ButtonAction(buttons[i],i);

        JButton button = new JButton(allActions[i]);

           panel.add(button);


        }

使用类 ButtonAction 如下

  public class ButtonAction extends AbstractAction 
  {
int i;
   public ButtonAction(String text, int i) {
    super(text);
    this.i = i;
    }
   public void actionPerformed(ActionEvent e) {
    /* you can put any action here. either make the action depend on array value or 
      the string text */
   System.out.println(i);

   }
 }
于 2012-11-04T15:00:39.560 回答