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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:40:00  来源:igfitidea点击:

How to make JavaFX Slider to move in discrete steps?

javajavafxintegersliderjavafx-8

提问by Mr Redstoner

I am making a GUIusing JavaFxand I need sliders that only allow integersto ever be selected.

我正在GUI使用JavaFx,我需要只允许integers选择的滑块。

I know I can use snapToTicks, but while pulling the "knob", it can still represent a non-integervalue. 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 valuePropertyof the Sliderand then you can either set the integer valueof the new Numbervalue:

您只需一个监听器添加到valuePropertySlider,然后你可以设置的整数值的新的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 的值:

can only select int values ranging from 1 to 4

只能选择 1 到 4 之间的 int 值