Search code examples
javajavafxjfoenix

How to edit JFXSpinner inner text


Is it possible to change the way the JFXSpinner progress text is displayed. I don't want it to be displayed as a percentage but as an index between 0 and 1.


Solution

  • So I've succeed by subclassing JFXSpinnerSkin and overriding layoutChildren. I get the Text node with Node#lookup() and change it's text. As the text wasn't centered anymore, I checked the source code, got the centering line and adapted it.

    public class SpinnerCustomSkin extends JFXSpinnerSkin {
        private SpinnerCustom control;
        private DecimalFormat formatter = new DecimalFormat("0.00");
    
        public SpinnerCustomSkin(SpinnerCustom control) {
            super(control);
    
            this.control = control;
        }
    
        @Override
        protected void layoutChildren(double contentX, double contentY, double contentWidth, double contentHeight) {
            super.layoutChildren(contentX, contentY, contentWidth, contentHeight);
    
            Text text = ((Text) getNode().lookup("Text"));
            text.setText(formatter.format(control.getProgress())); //Or whatever you want to display
            text.relocate((control.getRadius() - text.getLayoutBounds().getWidth()) / 2, (control.getRadius() - text.getLayoutBounds().getHeight()) / 2);
        }
    }
    

    Finnaly, I just subclassed the JFXSpinner element, maybe it's possible to set the skin by another way, but I didn't foud (in fact I didn't searched for so long).

    public class SpinnerCustom extends JFXSpinner {
        @Override
        protected Skin<?> createDefaultSkin() {
            return new SpinnerCustomSkin(this);
        }
    }