Search code examples
javaswingfor-loopjbuttonevent-listener

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

Solution

  • You should add b1 to jPanel and not new JButton(""+i)).

    jPanel4.add(b1);