Java JSlider 设置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6697780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:56:45  来源:igfitidea点击:

Java JSlider set values

javaswingrangejslider

提问by jpo

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

如何设置 a 的值JSlider?我想为它分配特定的值,间隔不是恒定的。请帮忙

回答by Mike Scott

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.

据我所知,滑块的范围是统一的,不能改变。(虽然我不确定这一点。)您可以做的是使用统一值并将其映射到您想要的间隔。例如,假设您希望滑块从 10 到 10000,但采用对数刻度。

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

将最小值设置为 1,(以 10 为底的对数 = 1),将最大值设置为 4(以 10,000 为底的对数)= 4。使用getValue()方法获取滑块的当前值并使用 将10 提高到该次方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 pagehas information on how to create custom labels. As pointed out hereyou would actually use a HashTablea class that implements theDictionaryinterface.

您可以使用setLabelTable(Dictionary labels)来设置自定义标签。此页面包含有关如何创建自定义标签的信息。正如这里所指出的,您实际上会使用一个HashTable实现Dictionary接口的类。

Cheers!

干杯!

回答by timaschew

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

使用 aBoundedRangeModel您可以修改此模型,因此您也可以同步 SJlider。

    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



或者,您可以使用 JSpinner:

    SpinnerModel spinnerModel = 
      new SpinnerNumberModel(value, minimum, maximum, stepSize);
    JSpinner spinner = new JSpinner(spinnerModel);

    // changing the stepSize at anytime
    sm.setStepSize(newValue);