Create a nice Codename One slider to notify a percentage

Viewed 115

Note for the readers: this question is specific for Codename One, it's not about css, html or similar.

My use case is to notify the user how much his/her profile is complete. I need to implement a slider like the following one, but after a lot of trials with the Slider component I didn't understood how to implement it. (Honestly I did not even understood how to start implementing it and I don't know if the Slider component is suitable.)

The width of this slider should be equal to the contentPane of the parent Form. Basically it is a rectangle with a small border: one part of the rectangle is coloured, the other is white, according to the percentage. Over the rectangle I need the percentage and a text: percentage and text are in a fixed position. The colour of the text changes according to the background colour, as it's shown in the second image.

Thank you for any help.

enter image description here enter image description here

1 Answers

This is pretty easy except for the color change. That portion requires hand coding of the graphics. I didn't run this code but it should be pretty close to how this should work:

class ProgressSlider extends Component {
    protected Dimension calcPreferredSize() {
        return new Dimension(convert(getDisplayWidth(), 6));
    }

    public void paint(Graphics g) {
         g.setColor(0xffffff);
         g.fillRect(getX(), getY(), getWidth(), getHeight());
         g.setColor(0);
         Font f = getStyle().getFont();
         g.drawString(progressPercetage, convert(4) + getX(), getY() + f.getHeight() / 2 + getHeight() - 2);
         g.drawString(progressText, convert(10) + getX(), getY() + f.getHeight() / 2 + getHeight() - 2);
         g.setColor(RED);
         g.fillRect(getX(), getY(), getWidth() / 100 * progressPercentage, getHeight());
         g.setColor(0xcccccc);
         g.drawRect(getX(), getY(), getWidth() - 1, getHeight() - 1);
         g.clipRect(getX(), getY(), getWidth() / 100 * progressPercentage, getHeight());
         g.setColor(0xffffff);             
         g.drawString(progressPercetage, convert(4) + getX(), getY() + f.getHeight() / 2 + getHeight() - 2);
         g.drawString(progressText, convert(10) + getX(), getY() + f.getHeight() / 2 + getHeight() - 2);
    }
}

This might be missing a few details like resetting the clipping region etc. I didn't run it but it should produce pretty much that result when tuned correctly. The text is drawn twice (second time with clipping) to replicate the color change effect.

Related