Add Action Listener to JButton Array

+1 Jonas Meise · March 27, 2015
Hey guys I am trying to program a calculator with JButtons and since a calculator has a lot of buttons I created them in an array called :
Then in this loop where I create them i add an action listener to each value. Here is the whole loop:

So here comes the problem. When i write this for each array value to get an action depending on which button I pressed it always activates all the if clauses. So whenI press Button 1 it will run operators.buttonNumbers(0), but also operators.buttonNumbers(1).

Does anyone know how I can prevent this from happening so it doesnt activate all the if statements?

Thanks for your help
LuPaw :)

Post a Reply


Oldest  Newest  Rating
+1 Branislav Lazic · March 27, 2015
You are encountering this issue because you are adding one same ActionListener to all buttons. ActionEvent ae is same for every button. 
When you ask ActionEvent ae: "Is button[0] source of ae ActionEvent the answer will be yes!"
If you ask: "Is button[1] source of ae ActionEvent the answer will be the same!"

Solution: Upon each iteration of your "for" loop add new instance of ActionListener to each button.

button.addActionListener(e -> {  // Do stuff!  });
0 Jonas Meise · March 28, 2015
Hmm I get the reason why it doesn't work but since I'm quite new to java I'm not sure what you mean with your solution. How would I add this instance in my code
+1 Branislav Lazic · March 28, 2015
I shown you already. 
Instead of passing anonymous inner class, in Java 8 you can pass lambda expression in your addActionListener method.

button.addActionListener(e -> { // Do stuff! });
0 Jonas Meise · March 28, 2015
Oh okay crap I have java 7 because I had a minecraft server guess I'll update to 8 then xP
thanks buddy :) 
0 Jonas Meise · March 29, 2015
Hmm Okay I've installed Java 8 and used the Lambda expression as you said so now when I click a button the method I call only gets called once. But somehow I don't get it to work that with a different button a different action happens now. I tried to call the method operators.buttonNumbers(i) with the variable i so it would be a different value for I depending on what button I press. The outcome altough is always 16. What am I doing wrong? Here is the code:
  • 1

Java / Android Development


Very popular language used to create desktop applications, website applets, and Android apps.

Bucky Roberts Administrator