简体   繁体   English

循环中按钮的 ActionListener 不起作用

[英]ActionListener for buttons in a loop not working

I have a jpanel in which i am add a variable number of buttons and then associating action listeners with each of them.我有一个 jpanel,我在其中添加了可变数量的按钮,然后将动作侦听器与它们中的每一个关联起来。 I add actionListener with the help of a loop.我在循环的帮助下添加了 actionListener。 but when I click the buttons nothing happens I have seen some other answers on the topic but they don't seem to work for me.但是当我单击按钮时,什么也没有发生,我看到了有关该主题的其他一些答案,但它们似乎对我不起作用。 Please point out my mistake.请指出我的错误。

    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());
    }

You should add b1 to jPanel and not new JButton(""+i)) .您应该将 b1 添加到 jPanel 而不是new JButton(""+i))

jPanel4.add(b1);

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

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