java 如何让 JavaFX Slider 以离散的步骤移动?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38681664/
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
How to make JavaFX Slider to move in discrete steps?
提问by Mr Redstoner
I am making a GUI
using JavaFx
and I need sliders that only allow integers
to ever be selected.
我正在GUI
使用JavaFx
,我需要只允许integers
选择的滑块。
I know I can use snapToTicks
, but while pulling the "knob"
, it can still represent a non-integer
value. I would like to get rid of that. It messes up other components linked to it.
我知道我可以使用snapToTicks
,但是在拉动 时"knob"
,它仍然可以代表一个non-integer
值。我想摆脱它。它弄乱了与之链接的其他组件。
Basically, I want something like Swing's JSlider
, but with JavaFx
. Is it possible? I have been searching but I can't find anything.
基本上,我想要类似的东西Swing's JSlider
,但是JavaFx
. 是否可以?我一直在寻找,但找不到任何东西。
回答by DVarga
You can simply add a listener to the valueProperty
of the Slider
and then you can either set the integer valueof the new Number
value:
您只需一个监听器添加到valueProperty
的Slider
,然后你可以设置的整数值的新的Number
价值:
slider.valueProperty().addListener((obs, oldval, newVal) ->
slider.setValue(newVal.intValue()));
or alternatively you can use integer rounding using Math.round
:
或者,您可以使用整数舍入使用Math.round
:
slider.valueProperty().addListener((obs, oldval, newVal) ->
slider.setValue(Math.round(newVal.doubleValue())));
回答by Arthur Va?sse
In FXML:
在 FXML 中:
<Slider fx:id="availableReproSelector"
blockIncrement="1.0"
cache="true"
majorTickUnit="1.0"
max="4.0"
min="1.0"
minorTickCount="0"
showTickLabels="true"
showTickMarks="true"
snapToTicks="true"
value="1.0"
/>
Or in Java:
或者在 Java 中:
Slider slider = new Slider(1, 4, 1);
slider.setBlockIncrement(1);
slider.setMajorTickUnit(1);
slider.setMinorTickCount(0);
slider.setShowTickLabels(true);
slider.setSnapToTicks(true);
The key here is the snap to ticks option combined with a proper combination of tick units. This setting results in the following slider which can only be used to select values ranging from 1 to 4 :
这里的关键是对齐刻度选项与刻度单位的正确组合。此设置导致以下滑块只能用于选择范围从 1 到 4 的值: