动态地向按钮添加动作侦听器

Dynamically adding action listener to buttons

我认为这是错误的。我希望我的代码在按钮为 created.Is 时立即添加 actionlistener 有一种方法可以动态地做到这一点。查看内部 for 循环,我在那里添加时遇到问题

import java.awt.*;
import java.applet.*;
import java.util.*;
import java.awt.event.*;

/* <applet code = "Gridl.java" width=300 height=200>
   </applet> */

public class Gridl extends Applet 
{
     TextField t1=new TextField("    ");

     public void init()
     {
         int n = 1;
         setLayout(new GridLayout(4,4));
         add(t1);
         setFont(new Font("Tahoma",Font.BOLD,24));

         for(int i=0;i<4;i++)
         {
             for(int j=0;j<4;j++)
             {
                 add(new Button(""+n));        
                 this.addActionListener(this);       // this didnt work :(
                 n++;
             }
         }  
    }

    public void actionPerformed(ActionEvent ae)
    {
        String str = ae.getActionCommand();
        t1.setText(str);
    }

}

在创建按钮时尝试这样 new button().add 而不结束该语句。

  new Button("").addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            System.out.println("You clicked the button");
        }
    });    

我认为您在此处的代码中反映了一些概念上的误解。重要的是要考虑将 ActionListener 添加到哪个组件。目前,您的代码将 ActionListener 添加到扩展 Applet 的 Gridl 对象,而不是按钮本身。它不会抛出异常,因为那是有效的,但它不会给你你想要的行为

为了让你工作,我建议你更换

add(new Button(""+n));

Button b = new Button(""+n);
b.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e)
    {
        System.out.println("You clicked button "+e.getSource().toString());
    }
});

this.add(b);

请注意,这会为每个 Button 对象设置一个新的 ActionListener,其行为取决于您在 actionPerformed() 方法中放置的内容。您可以对所有按钮使用相同的行为,也可以对每个按钮使用不同的行为。

我建议您阅读 oracle Java Swing GUI 教程,尤其是 one on actions。那里也有代码示例。

编辑:

我发现您可能想让 Gridl 成为所有按钮的侦听器。在这种情况下 - 您可以通过以下方式实现:

public class Gridl extends Applet implements ActionListener
{
     TextField t1=new TextField("    ");

     public void init()
     {
         int n = 1;
         setLayout(new GridLayout(4,4));
         add(t1);
         setFont(new Font("Tahoma",Font.BOLD,24));

         for(int i=0;i<4;i++)
         {
             for(int j=0;j<4;j++)
             {
                 Button b = new Button(""+n));        
                 b.addActionListener(this);
                 this.add(b);
                 n++;
             }
         }  
    }

    public void actionPerformed(ActionEvent ae)
    {
        String str = ae.getActionCommand();
        t1.setText(str);
    }

}