The button
variable is being redefined everytime you run the loop, so when you finally call your actionPerformed
method, you are reading the data of the last button. The loop finished before any event happened and saved the reference of the last button created in the button
variable.
You need to reference the button
from the event object, because it contains a reference to the button that is the source of the event:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//should print out the location of the button that was clicked
System.out.println( ((JButton)e.getSource()).getLocation() );
}
});
The addActionListener
method is called 20 times, but the actionPerformed
method is called asynchronously and only when an action event (ex: button click) happens. The ActionEvent object contains information about the event, which includes the source of the event, which is your button.