Button 为方法创建的按钮添加操作侦听器

Button 为方法创建的按钮添加操作侦听器,button,actionlistener,Button,Actionlistener,好的,如果我有以下代码: protected void makebutton(String name){ JButton button = new JButton(name); mypanel.add(button); } 然后: makebutton("Button1"); makebutton("Button2"); makebutton("Button3"); 如何将ActionListener添加到它们中。我用什么名字来命名Actio

好的,如果我有以下代码:

protected void makebutton(String name){

         JButton button = new JButton(name);

         mypanel.add(button);
     }
然后:

makebutton("Button1");
makebutton("Button2");
makebutton("Button3");

如何将ActionListener添加到它们中。我用什么名字来命名ActionListener,尝试了很多组合,但都没有成功

您可以做的是使该方法返回一个按钮。这就是在程序的其他地方使用按钮变量的方法。你的情况是按钮被封装了。因此,您无法从代码中的任何其他位置访问。像这样的

private JButton makeButton(String name){
    JButton button = new JButton(name);

    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            // code action to perform
        }
    });
    return button;
}
您可以在声明按钮时使用该方法

JButton aButton = makeButton();
panel.add(aButton);
更合理的方法是只创建按钮而不使用方法

JButtton button = new JButton("Button");
panel.add(button);

button.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        // code action to perform
    }
});
我真的不认为有必要找到一种方法

另一个选项是创建自定义侦听器类

public class GUI {
    JButton button1;
    JButton button2;

    public GUI(){
        button1 = new JButton();
        button2 = new JButton();
        button1.addActionListner(new ButtonListener());
        button2.addActionListner(new ButtonListener());
    }

    private class ButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            if (e.getSource() == button1){
                // do something
            } else if (e.getSource() == button2){
                // something
            }
        }
    } 
}
您必须为每个按钮创建更多的方法。
我认为peeskillet的第二个代码是好的。

好的。它会对所有按钮应用相同的操作还是只对一个按钮应用相同的操作?第一个代码,是的。这就是你想要的吗?如果没有,那么我会选择第二种方法。我使用计量器,因为它可以更快地添加xy个按钮。我知道其他创建按钮并向其添加actionlistener的示例。但是,如果我用方法创建xy按钮,我如何向每个按钮添加actionlistener,因此按钮的操作不同,或者这是不可能的,我必须用另一种方法,一个按钮一个按钮地进行操作?如果您希望每个按钮都有不同的操作,不要期望这是一个快速的过程。您仍然需要编写不同操作的代码。
protected void makebutton(String name){
    final String n = name;
    JButton button = new JButton(name);

    mypanel.add(button);
    button.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if(n=="Button1"){
                button1ActionListener();
            }else if(n=="Button2"){
                button2ActionListener();
            }
        }
    });
 }