我想问一个有关动态button actionPerformed的问题。我的内容菜单带有jFrame,该菜单将通过jPanel1cardLayout引用动态jButton1。动态jPanel1包含saveButton。我将Test ActionListener附加到jButton1。我面临的问题是我已将actionCommand设置为jPanel1.saveButton,如下面的代码所示。当我单击jButton1输出时,将得到23。我预计还单击了2nd3rd jPanel1.SaveButton,但是只单击了3rd jPanel1.saveButton。如何获得2nd3rd jPanel1.SaveButton被单击的信息?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

public class Test implements ActionListener {

    public Test() {
    }

    public void actionPerformed(ActionEvent e) {

        for (int i = 0; i<2; i++){
           jPanel1.save.setActionCommand(String.valueOf(i+2));
           String n = jPanel1.save.getActionCommand();
           jPanel1.save.doClick();
           System.out.println("jPanel1: " + n);
        }

           System.out.println("The action have been performed");
    }

    public static void main(String[] agrs) {
           JButton but = new JButton();
           but.addActionListener(new Test());
           but.doClick();
    }
}

Output:
jPanel1: 2
jPanel1: 3

最佳答案

如果希望每个ActionListener实例引用一个不同的JPanel,则可以将对该“ JPanel”的引用传递给其构造函数:

JPanel panel1 = new JPanel();
JButton but = new JButton();
but.addActionListener(new Test(panel1));


并更改构造函数以使用该引用:

JPanel panel;
public Test(JPanel panel) {
    this.panel = panel;
}

09-12 18:03