我有一个jpanel,其中添加了可变数量的按钮,然后将动作侦听器与每个按钮相关联。 我借助循环添加actionListener。 但是当我单击按钮时,什么也没发生 我还看到了有关该主题的其他答案,但它们似乎对我没有用。 请指出我的错误。
jPanel4.setLayout(new GridLayout(20,2));
for(int i=1;i<=40;i++){
JButton b1=new JButton(""+i);
jPanel4.add(new JButton(""+i));
b1.addactionListener(new actionListener(){
@Override
public void actionPerformed(actionEvent evt){genactionPerformed(evt);}
});
}
private void genactionPerformed(actionEvent evt){
JOptionPane.showmessagedialog(null,"You clicked" +evt.getactionCommand());
}