Search code examples
javaswingjslider

Custom range to use with JSlider


I'm trying to create a jslider that moves withing the following ranges.

[-x,-1)[1,x]

In short I don't want the values -1 and 0 to be valid values for the JSlider. But the values from x to -1 should be allowed, and 1 to x should be allowed.

I'm trying to not write hacky code, so I don't want to write a function in the UI code that just gets the value from a different (continuous) range, and then transforms it to the range I want with a bunch of it statements.

Ideally, I should just be able to call slider.getValue() and know that the return value will be in the range I described above.


Solution

  • I think you must do this value adjustment yourself perhaps within overridden method setValue()?

    Try out this code:

        int x = 10;
        @Override
        public void setValue(int n)
        {
            if((n >= -x && n < -1)|| (n =< x && n >= 1))
            {   
                super.setValue(n);
                System.out.println("OI in setValue");
            }
        }