Search code examples
javafor-loopjbuttonactionlistener

Having a different action for each button dynamically created in a loop


use this website a lot but first time posting. My program creates a number of buttons depending on the number of records in a file. E.g. 5 records, 5 buttons.

The buttons are being created but i'm having a problem with the action listener.

If add the action listener in the loop every button does the same thing; but if I add the action listener outside the loop it just adds the action listener to last button.

Any ideas?

Here is what I have code-wise (I've just added the for loop to save space):

int j=0;
for(int i=0; i<namesA.size(); i++)
{
    b = new JButton(""+namesA.get(i)+"");
    conPanel.add(b);
    conFrame.add(conPanel);

    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae2){

                System.out.println(namesA.get(j));

        }
    }});
    j++;
}

Much Appreciated


Solution

  • As you are creating one action listener for each button that you are creating, you could have this:

    final int buttonIndex = i;
    b.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent ae2) {
           System.out.println("Button pressed is: " + buttonIndex);
       }
    }
    

    To access a variable inside an anonymous class method, it has to be marked final. That's what you have that final int buttonIndex = i; statement.

    You can use the setActionCommand method on the button to define an action command to it that you could retrieve from the actionCommand property of the ActionEvent class. By doing that, you could have the same listener for all your buttons. You could set that action command to the buttonIndex variable that I defined in your example. By doing that, you create less anonymous class in your application, which is always good (less objects consuming less memory).