我想问一个有关动态button
actionPerformed
的问题。我的内容菜单带有jFrame
,该菜单将通过jPanel1
和cardLayout
引用动态jButton1
。动态jPanel1
包含saveButton
。我将Test ActionListener
附加到jButton1
。我面临的问题是我已将actionCommand
设置为jPanel1.saveButton
,如下面的代码所示。当我单击jButton1
输出时,将得到2
和3
。我预计还单击了2nd
和3rd
jPanel1.SaveButton
,但是只单击了3rd
jPanel1.saveButton
。如何获得2nd
和3rd
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;
}