Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX: difference between methods setOnMouseClicked() and addEventHandler()?

When I have an object o and I want to add an event to it, lets say I want it changes its color when clicked (Let's say it's a Rectangle object). What is the difference between: o.setNonMouseClicked(){ ... } and

o.addEventHandler(Action.EventAction, new EventHandler<ActionEvent>(){ ... })

How can I make the right choise?

like image 988
bog Avatar asked Apr 29 '26 23:04

bog


1 Answers

Well it depends on the situation.

The "setOnMouseClicked" will add a new EventHandler to your object. But it will also replace any eventHandler previously added through that method! So if you're planning on changing in runtime the way to react to mouse click, this is the right method.

Now if you just want to add another eventHandler (or several), you should use the "addEventHander" method. Therefore you will have your handlers added on one side. And you will keep the eventHandler added through "setOnMouseClicked" if previously added.

Also beware of the eventHandler or listener you're added because they can lead to severe memory leaks so be sure to remove them when necessary.

like image 140
Maxoudela Avatar answered May 01 '26 12:05

Maxoudela



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!