Search code examples
javaswingjslider

Moving 2 sliders together


I am currently making a program for school where I have to lock the ratio while adjusting JSliders.

I could not figure out how to make one slider change with the same value while changing the first slider. I want to change the sliders at a 1:1 ratio, so if I slide width up 5, the length will also go up 5, but I couldn't figure out how to find a constant difference to calculate when I change the value.


Solution

  • In your code you are setting length value based on length.getValue, but you want length to be set as width changes and vise versa. So I suggest that you set length like length.setValue(width.getValue());

     if(lkRatio.isSelected() !=true){
        tempw = width.getValue();
        templ = length.getValue();
        diff = width.getValue() - length.getValue();
    }
    
    
    if(lkRatio.isSelected()){
    
      if(source == width){
        length.setValue(width.getValue() - diff);
      }
    
      if(source == length){
           width.setValue(length.getValue() + diff);
      }
    }