javaswingactionlistenerjslider

Bind JSlider knob to an external int value


My JSlider has a iconScaleManager as an attribute. The iconScaleManager possesses a int which value corresponds to the JSlider ticks. That int is modified by another class, an ActionListener, which is added on 2 JButtons.

The goal is : I would like the knob to move, on its own, to the actual value of the int which corresponds to the tick mark. I guess I need to bind the value or to fire an event, but I couldn't figure how to.

And of course, I added aChangeListener on the JSlider :

public class SliderListener implements ChangeListener {
     private int sliderIndex = 0;
     private IconScaleManager iconScaleManager = null;

     public SliderListener(int startingIndex, IconScaleManager renderer) {
         sliderIndex = startingIndex;
         iconScaleManager = renderer;
     }

     @Override
     public void stateChanged(ChangeEvent e) {
         JSlider source = (JSlider)e.getSource();
         sliderIndex = source.getValue();
         iconScaleManager.scaleSlider(sliderIndex);
     }  
}

Solution

  • For simpler use, I made the button's ActionListener change the state of the JSlider (setValue(iconScaleManager.getScaleIndex())) in actionPerformed(). (It was simpler than I thought). Thanks to @MadProgrammer.

    public class ZoomListener implements ActionListener {
        private boolean zoomIn = false;
        private JSlider zoomSlider = null;
        private IconScaleManager iconScaleManager = null;
    
        public ZoomListener(boolean zoom, JSlider slider, IconScaleManager renderer) {
            zoomIn = zoom;
            zoomSlider = slider;
            iconScaleManager = renderer;
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            iconScaleManager.scaleButton(zoomIn);
            System.out.println(iconScaleManager.getScaleIndex());
            zoomSlider.setValue(iconScaleManager.getScaleIndex());
        }
    }