How to make JavaFX Slider to move in discrete steps?

青春壹個敷衍的年華 提交于 2019-12-08 14:58:07

问题


I am making a GUI using JavaFx and I need sliders that only allow integers to ever be selected.

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.

Basically, I want something like Swing's JSlider, but with JavaFx. Is it possible? I have been searching but I can't find anything.


回答1:


You can simply add a listener to the valueProperty of the Slider and then you can either set the integer value of the new Number value:

slider.valueProperty().addListener((obs, oldval, newVal) -> 
    slider.setValue(newVal.intValue()));

or alternatively you can use integer rounding using Math.round:

slider.valueProperty().addListener((obs, oldval, newVal) ->
    slider.setValue(Math.round(newVal.doubleValue())));



回答2:


In 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:

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 :



来源:https://stackoverflow.com/questions/38681664/how-to-make-javafx-slider-to-move-in-discrete-steps

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