Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+7 votes

Can I make a button run a function with a parameter so I can have buttons that work only slightly differently.

asked in CSC 305 Fall 2024 by (1.1k points)

1 Answer

+7 votes
 
Best answer

I am not sure how you would get a parameter to put into the method from clicking a button.

If you want to have two separate buttons that call the same method, but have slightly different outcomes, you could do a couple of things:

  • You could have the common functionality of the two buttons be a separate method, and then have the two buttons call different methods that would both call the method that has the similar code
  • You could have both buttons call the same method, but then inside of the method you could check to see what button was pressed. So you could just call button.getText() to see what the button is named, and then have the different buttons do different things inside of the method.
answered by (1.5k points)
selected by
+2

I want to update my answer, because I realize that you can actually put a parameter into a method call from a button. If you want to have different functionality from the same button, but have it do different things due to some outside variable, then you can pass in that value when you are setting the onAction for the button.

So for example, I have a "startSim" button, but it needs a couple of parameters to start the sim, so when I set the onAction method for the button, I passed in the value from one of our sliders as a parameter of the method. so the code looks something like, button.onAction(evt -> startSim(slider.getValue());

...