Re: How to lock 3 JSliders together
jcsnippets.atspace.com wrote:
"TonyZ" <tonyz@link-research.com> wrote in message
news:1150386559.321223.195020@i40g2000cwc.googlegroups.com...
Hi all,
I have 3 JSliders and I want the option of locking their movement
together. I use
a checkbox labeled "Lock Sliders" to determine whether the sliders
should be locked or not.
I thought I could do this by using the "setValue()" method on the two
sliders that were not
being draged. For example, if the user was dragging slider A, I would
set the value of B and C in the Change Listener routine.
The problem is that the setValue() fires a changed state for the B and
C sliders (each of
which, in turn, fires a changed state for the other two, causing a big
problem).
<snipped>
I have not tried this, but here is my opinion which you could try:
- add a Change Listener
- if one of the three sliders is changed, update the others with setValue
This part you have already done. The problem is in the fact that a changed
state is fired for the two sliders that were altered by setValue(). Let
these fire.
The trick, imho, is to check first whether the value is already equal to the
one you want to set. This way, you can stop the domino effect of events
getting fired.
Change A -> B and C get changed as well.
B fires a changed state, and wants to change C and A. There are already
changed, and the chain will stop.
Similar situation for C.
I don't know whether or not this will work, but I assume it will - please
try it, and post your findings, as this is an interesting problem I haven't
encountered yet.
Alternatively, use a flag to indicate that you are updating, and simply
return if true;
private boolean changing = false;
private JSlider[] sliders; // your sliders you want to sync
public void propertyChanged(PropertyChangeEvent evt) {
if (changing) return;
changing = true;
int value = ((JSlider)evt.getSource()).getValue();
for (int i=0; i<sliders.length; i++)
if (sliders[i] != evt.getSource())
sliders[i].setValue(value);
changing = false;
}
The boolean "changing" flag basically prevents reentrance of the method
while it is already handling an event.
Rogan