为方法创建的按钮添加Action侦听器



如果我有以下代码,那就好了:

protected void makebutton(String name){
         JButton button = new JButton(name);
         mypanel.add(button);
     }

然后:

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

如何将ActionListener添加到它们中。我用哪个名字作为ActionListener,尝试了很多组合,但都没有成功。

您可以做的是让方法返回一个Button。这就是您可以在程序中的其他位置使用按钮变量的方法。在您的案例中发生的事情是按钮被封装了。因此,您无法从代码中的其他位置进行访问。像这样的

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
            }
        }
    } 
}
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();
            }
        }
    });
 }

您必须为每个按钮创建更多的方法。我认为peeskillet的第二个代码是好的。

最新更新