3

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?

  • you have to carefull and the look and feel you use!(different look&feel means different react.. After you set the bar StringPainted().. and .setForeground(Color.(your choice) if you don't see reactions use barname.setOpaque(true); – crAlexander Feb 04 '15 at 14:59

2 Answers2

5

Looking at the source code, this won't be easy.

The color is stored in the BasicProgressBarUI class:

  • In the constructor the color is retrieved from the UIManager using a static method. Static method means you cannot overwrite the call.
  • Colors are stored as private fields, and the class only expose protected getters, no setters. No setters mean you cannot call it externally.

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:

  • This allows you to create your own UI instance
  • This allows to override the protected getters

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.

Robin
  • 36,233
  • 5
  • 47
  • 99
0

You could set the setStringPainted property to true:

progressBar.setStringPainted(true);
progressBar.setForeground(Color.blue);
progressBar.setString("10%");
user3041058
  • 1,520
  • 2
  • 12
  • 16
  • The setStringPainted property determines whether or not the string will appear on the progress bar, not whether or not the string is painted a different colour. – aakk Aug 07 '17 at 12:21