-1

I have this piece of code:

Timer timer;
ActionListener listener;
listener = new ActionListener() {
    int counter = 0;

    public void actionPerformed(ActionEvent ae) {
        counter++;
        jSlider1.setValue(counter);
        jSlider2.setValue(counter);
        jSlider3.setValue(counter);
        jSlider4.setValue(counter);
        jSlider5.setValue(counter);
        jSlider6.setValue(counter);
        jSlider7.setValue(counter);
        jSlider8.setValue(counter);
        jSlider9.setValue(counter);
        jSlider10.setValue(counter);
    }
};
timer = new Timer(50, listener);
timer.start();

The JSLider moves automatically.

How to make the slider so that when it reaches the end, it goes back to the beginning?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
chicoo
  • 1

1 Answers1

1

reverse the counter

So, you need some value which dictates the amount to add/subtract from the counter on each tick. You probably also need to know the min/max range the counter can travel through.

To this end, a simple delta value, which gets added to the counter and which can be inverted (+/-) when the counter reaches either end of the available range.

Maybe something like...

listener = new ActionListener() {
    int counter = 0;
    int delta = 1;

    int min = 0;
    int max = 100;

    public void actionPerformed(ActionEvent ae) {
        counter += delta;
        if (counter < min || counter > max) {
            delta *= -1;
        }
        counter = Math.min(max, Math.max(min, counter));

        jSlider1.setValue(counter);
        jSlider2.setValue(counter);
        jSlider3.setValue(counter);
        jSlider4.setValue(counter);
        jSlider5.setValue(counter);
        jSlider6.setValue(counter);
        jSlider7.setValue(counter);
        jSlider8.setValue(counter);
        jSlider9.setValue(counter);
        jSlider10.setValue(counter);
    }

};
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366