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 :
button[]
Then in this loop where I create them i add an action listener to each value. Here is the whole loop:

/images/forum/upload/2015-03-27/33395cf16f90e66a75a2a222016154df.PNG
/images/forum/upload/2015-03-27/be39bc3c423e7303453a5c986aa55c45.PNG
...
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

Replies

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
/images/forum/upload/2015-03-28/134449f844a8b9397f7499c85fed47f9.PNG
+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:
/images/forum/upload/2015-03-29/302dc96e08e6d915e9addb1605ac7ac7.PNG
  • 1

Java / Android Development

107,254 followers
About

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

Links
Moderators
Bucky Roberts Administrator