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

+10 votes

I am doing Lab 1 and there is a part where one click of button will update two labels. However, when I use two setOnAction() for the same button:

btn1.setOnAction(evt -> updateLabel1(xyz));
btn1.setOnAction(evt -> updateLabel2(abc));

it does not work. Is there any ideas how to have 2 events for the same button? Thanks!

asked in CSC 305 Fall 2024 by (594 points)

3 Answers

+4 votes
 
Best answer

As you discovered, the setOnAction(...) specifies the single event handler code that will be called whenever an action event occurs on the button.

Thus, your second line of code causes the event handler to only run the updateLabel2() code and thus not run the updateLabel1() code anymore.

I think the simplest/best way to handle this is to take the approach suggested by Rory and Mehdi, and just have one event handler that does two things. You could either do this:

btn1.setOnAction(evt -> { updateLabel1(xyz); updateLabel2(abc);} );

Or

btn1.setOnAction(evt -> updateLabels(xyz, abc) );

However, it actually IS possible to add MULTIPLE event handlers to a given
, but you have to use the addEventHandler method, instead of the simpler .setOnAction

    btn1.addEventHandler(ActionEvent.ACTION, evt -> updateLabel1(xyz)));
    btn1.addEventHandler(ActionEvent.ACTION, evt -> updateLabel2(abc));

(But I think this approach results in less clean code, and it's not needed in this situation.)

answered by (2k points)
selected by
+4 votes

Make another function that takes both those events, and then it should be fine

function updateLebels(x1,x2){
updateLabel1(x1)
updateLabel2(x2)
}

this is not in Java, I don't want to think to type the function but you get the point lol

answered by (659 points)
+3 votes

I don't think there is a way to do that. However you should be able to make a function that does everything and then call that function when the button is pressed.

answered by (1.1k points)
...