Mr Redstoner Mr Redstoner - 4 months ago 70
Java Question

JavaFx Slider integer only

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.

Answer

You can try to simply add a listener to the valueProperty and 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())));