开发者

Avoiding unnecessary events and infinite loop in "coupled" JSliders?

开发者 https://www.devze.com 2022-12-27 06:58 出处:网络
I have a GUI that is issuing commands to a web server based on slider values. 开发者_JAVA技巧Some of these sliders are \"coupled\" on the web server, so changing one of them may also change another on

I have a GUI that is issuing commands to a web server based on slider values. 开发者_JAVA技巧Some of these sliders are "coupled" on the web server, so changing one of them may also change another one. The coupling is accomplished by the web server returning a list of the values that were set based on the the issued command.

So I can easily set the appropriate sliders based on this response, but the issue is that doing this causes the ChangeListener to be fired and then a command is issued to the web server again. Ideally, the "coupling" should be well behaved and avoid infinite loops, but that is a potential concern and send all those extra events seems unnecessary.

The two solutions I could think of were:

  1. Temporarily removing the listeners, changing the value, and then putting them back.
  2. Add a "manual" flag to let the listener know that it should ignore the change.

Neither of those seems like the ideal solution to me, but is one of them "better" than the other? Or is there a third solution that I'm not considering?


add an enabled flag to the listeners and disable them before manually setting the value

I wouldn't add and remove listeners as that just triggers more listeners!


One author calls this problem fibrillation. This discussion suggests a shared model, in addition to the flag approach suggested by @Pyrolistical.


The standard model used in .Net WPF is to fire an event only if value of the property has changed! In your case it is setValue() method.


After struggling with this for a while and going into a mess with various booleans, I found that the solution was to simply add a check for hasFocus and respond accordingly.

  • If a field did NOT have focus, then it would allow an update to itself, but wouldn't trigger updates to any other field.

  • If a field DID have focus, then it would trigger changes to other fields.

This way, only the focused field can trigger any change and there is no infinite loop. The code is readable and simple, now, and the logic is easy to follow and update.

0

精彩评论

暂无评论...
验证码 换一张
取 消