我想问一个与动态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
答案 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;
}