I have a JProgressBar called playerhealth. I the the color of the bar to green. This makes the text hard to see, so I want to set the color of the text inside the JProgressBar to be black.
I read that you can use UIManager to set the global color of JProgressBars, but I only want to do it for this one (and another, but that doesn't matter).
I also read HERE that my only other option is to alter the JProgressBar class. How would I go about this?
Looking at the source code, this won't be easy.
The color is stored in the BasicProgressBarUI class:
UIManager using a static method. Static method means you cannot overwrite the call.The ProgressBarUI instance which is used for the JProgressBar is derived from the UIManager (UIManager#getUI), which is again a static method.
That leaves us with not that many options. What I think is a viable one is to use the JProgressBar#setUI method:
Major drawback for this approach is that it requires that you know up-front which Look and Feel your application will be using. For example if the application is using Metal, this would become
JProgressBar progressBar = ... ;
ProgressBarUI ui = new MetalProgressBarUI(){
/**
* The "selectionForeground" is the color of the text when it is painted
* over a filled area of the progress bar.
*/
@Override
protected Color getSelectionForeground() {
//return your custom color here
}
/**
* The "selectionBackground" is the color of the text when it is painted
* over an unfilled area of the progress bar.
*/
@Override
protected Color getSelectionBackground()
//return your custom color here
}
}
progressBar.setUI( ui );
Not 100% happy with this solution due to the major drawback of having to know the look-and-feel up-front.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With