Search code examples
javaswingcolorsjslider

color java JSlider based on tick value


I want to have a JSlider with three kind of colors each one occupying a range of values(eg. 1 to 10 is green, 10 to 20 is yellow, 20 to 30 is red), how can this be implemented?


Solution

  • Edit:

    Oops, for some reason I thought there was a paintBackground() method in JComponent. I guess you'd instead have to do setOpaque(false) (so that super doesn't paint the background) and then override paintComponent() like this:

    protected void paintComponent(Graphics g) {
       int w = getWidth();
       int h = getHeight();
       int x1 = w / 3;
       int x2 = w * 2 / 3;
    
       g.setColor(Color.GREEN);
       g.fillRect(0, 0, x1, h)
       g.setColor(Color.YELLOW);
       g.fillRect(x1, 0, x2 - x1, h)
       g.setColor(Color.RED);
       g.fillRect(x2, 0, w - x2, h)
    
       super.paintComponent();
    }