让JSlider不断移动

时间:2018-05-10 00:14:53

标签: java swing jslider

我有这段代码:

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();

JSLider自动移动。

如何制作滑块,以便当它到达结尾时,它会回到开头?

1 个答案:

答案 0 :(得分:1)

  

反转计数器

因此,您需要一些值来决定每个countertick的加/减数额。您可能还需要知道counter可以通过的最小/最大范围。

为此,一个简单的delta值会被添加到counter,并且当counter到达可用范围的任一端时可以反转(+/-)

也许像......

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);
    }

};