Changing the color of energy bars depending on their values?

I created this method to check the value in my execution line. It works as expected when it decreases, i.e. Turns red, yellow and orange. But when I increase the value, the color is not updated. So when it is below 25 and turns red, it stays the same color as I increase the value of the energy bar. What am I doing wrong here? thank you in advance.

public void checkEnergyBar(JProgressBar EnergyBar){
    if(EnergyBar.getValue()<25){
        EnergyBar.setForeground(Color.RED);
    }else if(EnergyBar.getValue()<51){
        EnergyBar.setForeground(Color.YELLOW);
    }else if(EnergyBar.getValue()<76){
        EnergyBar.setForeground(Color.orange);
    }else if(EnergyBar.getValue()<101){
        EnergyBar.setForeground(Color.GREEN);
    }

     EnergyBar.repaint();

}

      

I made these changes and still have no joy.

public void checkEnergyBar(JProgressBar EnergyBar){
    if(getEnergy()<26 ){
        EnergyBar.setForeground(Color.RED);
    }else if(getEnergy()<51 || getEnergy()>26){
        EnergyBar.setForeground(Color.YELLOW);
    }else if(getEnergy()<76 || getEnergy()>51){
        EnergyBar.setForeground(Color.orange);
    }else if(getEnergy()<101 || getEnergy()>76){
        EnergyBar.setForeground(Color.GREEN);
    }

     EnergyBar.repaint();

}

      

+3


source to share


1 answer


Personally, I believe the JProgressBar is listening. I have my own, more customizable way to create a progress bar.

Instead of using a pre-built JProgressBar, use the original way of displaying graphics: Canvas

Subclass the canvas, then override the paint method, add variables to represent the color and value, and add the setValue method. In the paint method, set the color based on the value, setForeground (color), and then just use the graphics argument to draw the rectangle (0,0, value, getHeight ()).



This is how I would make a progress bar. This also has the advantage that: A) You can add a border and background color to the canvas, just like a progress bar B) You can use graphics.paintImage and scale / crop the image to your desired size

Hope this helped with your progress bar :)

0


source







All Articles