Java JSlider set values

15,720

Solution 1

You can set the min and max values of the slider with the constructor:

JSlider mySlider = new Slider(10, 30); // min value of slider, maxValue of slider

As far as I know the range of the slider is uniform and can't be changed. (I am not certain of this though.) What you could do is use the uniform value and map it to the intervals you want. For example, lets' say you want the slider to go from 10 to 10000, but at a logarithmic scale.

Set the min value to 1, (log base 10 of 10 = 1), the max value to 4 (log base 10 of 10,000) = 4. Get the current value of the slider using the getValue() method and raise 10 to that power with Math.pow().

Or you could store the values corresponding to the slider positions with the values you want in array if they cannot be computed.

You can use the setLabelTable(Dictionary labels) to set custom labels. This page has information on how to create custom labels. As pointed out here you would actually use a HashTable a class that implements theDictionary interface.

Cheers!

Solution 2

Use a BoundedRangeModel You can modify this model and so you synchronize the SJlider too.

    BoundedRangeModel bRangeModel = 
      new DefaultBoundedRangeModel(initValue, extent, min, max);
    JSlider s = new JSlider(bRangeModel);

But the step size isn't bound to the model. You can set the step with the minor tick spacing (I think that it's what you want)

    slider.setMinorTickSpacing(5); // step / interavl
    slider.setSnapToTicks(true); // should be activated for custom tick space


Alternatively you can use a JSpinner:
    SpinnerModel spinnerModel = 
      new SpinnerNumberModel(value, minimum, maximum, stepSize);
    JSpinner spinner = new JSpinner(spinnerModel);

    // changing the stepSize at anytime
    sm.setStepSize(newValue);
Share:
15,720
jpo
Author by

jpo

Updated on July 01, 2022

Comments

  • jpo
    jpo almost 2 years

    How can I set the values of a JSlider? I want to assign it specific values, with intervals that are not constant. Please help

  • timaschew
    timaschew almost 9 years
    which version of java / swing are you using? My answer is from 2011! This worked in Java 6
  • phil294
    phil294 almost 9 years
    alright, seems the fault was on my side: setSapToTicks just happens on mouse click RELEASE - the actual moving of the slider is not step-able. if one can live with that, it works now^^ thanks