简体   繁体   中英

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. I add actionListener with the help of a loop. 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)) .

jPanel4.add(b1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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