Java JSlider set values

你。 提交于 2019-12-23 20:35:22

问题


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


回答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!




回答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);


来源:https://stackoverflow.com/questions/6697780/java-jslider-set-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!