Friday, May 16, 2014

Styling the progress color a ProgressIndicator along a gradient

I thought it would be fun to have ProgressIndicator that went from red, to yellow, to green as the progress value went from zero to one. So I cooked this up. The color transitions nicely along a gradient from red at 0%, yellow at 50%, and green at 100%. Note the use of Bindings.createStringBinding, too.  Oh, and a lambda thrown in for good measure!

        // styled ProgressIndicator
        final ProgressIndicator progressIndicator = new ProgressIndicator();
        progressIndicator.setPrefSize(100, 100);
        progressIndicator.styleProperty().bind(Bindings.createStringBinding(
                () -> {
                    final double percent = progressIndicator.getProgress();
                    if (percent < 0) return null; // progress bar went indeterminate
                    //
                    // poor man's gradient for stops: red, yellow 50%, green
                    // Based on http://en.wikibooks.org/wiki/Color_Theory/Color_gradient#Linear_RGB_gradient_with_6_segments
                    //
                    final double m = (2d * percent);
                    final int n = (int) m;
                    final double f = m - n;
                    final int t = (int) (255 * f);
                    int r = 0, g = 0, b = 0;
                    switch (n) {
                        case 0:
                            r = 255;
                            g = t;
                            b = 0;
                            break;
                        case 1:
                            r = 255 - t;
                            g = 255;
                            b = 0;
                            break;
                        case 2:
                            r = 0;
                            g = 255;
                            b = 0;
                            break;

                    }
                    final String style = String.format("-fx-progress-color: rgb(%d,%d,%d)", r, g, b);
                    return style;
                },
                progressIndicator.progressProperty()
        ));

2 comments:

  1. I forgot to mention that this code just went into the Ensemble8 Progress Indicator sample for JavaFX 8u20

    ReplyDelete