动态jPanel按钮动作命令

时间:2016-09-16 11:49:08

标签: java swing jbutton

我想问一个与动态button actionPerformed相关的问题。我的jFrame内容菜单会引用动态jPanel1 cardLayoutjButton1。动态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

1 个答案:

答案 0 :(得分:2)

如果您希望每个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;
}