简体   繁体   English

动态jPanel按钮actionCommand

[英]dynamic jPanel buttons actionCommand

I would like to ask a question related to dynamic button actionPerformed . 我想问一个有关动态button actionPerformed I have jFrame with content menu which will reference to dynamic jPanel1 by cardLayout and jButton1 . jFrame与将参考动态内容菜单jPanel1通过cardLayoutjButton1 Dynamic jPanel1 contain saveButton . 动态jPanel1包含saveButton I attached Test ActionListener to jButton1 . 我将Test ActionListener附加到jButton1 The problem that I am facing is I have set actionCommand to jPanel1.saveButton as shown in below code. 我面临的问题是我已将actionCommand设置为jPanel1.saveButton ,如下面的代码所示。 And when I click jButton1 output I am getting 2 and 3 . 当我单击jButton1输出时,得到23 I was expected that 2nd and 3rd jPanel1.SaveButton also was clicked, but just 3rd jPanel1.saveButton was clicked. 我希望2nd3rd jPanel1.SaveButton也被单击,但是只有3rd jPanel1.saveButton被单击了。 How do I get that 2nd and 3rd jPanel1.SaveButton were clicked? 如何获得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

If you want every ActionListener instance refer to a different JPanel you can pass a reference to that `JPanel' to its constructor : 如果您希望每个ActionListener实例引用一个不同的JPanel ,则可以将对该“ JPanel”的引用传递给其构造函数:

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

And change the constructor to use that reference: 并更改构造函数以使用该引用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM