设置 JProgressBar TEXT 颜色

Mat*_*erg 3 java swing colors jprogressbar

我有一个名为 playerhealth 的 JProgressBar。我把条的颜色改为绿色。这使得文本难以看到,所以我想将 JProgressBar 内的文本颜色设置为黑色。

我读到你可以使用 UIManager 来设置 JProgressBars 的全局颜色,但我只想为这个(和另一个,但这并不重要)做。

我还在这里读到我唯一的其他选择是更改 JProgressBar 类。我该怎么办?

Rob*_*bin 5

查看源代码,这并不容易。

颜色存储在BasicProgressBarUI类中:

  • 在构造函数中,UIManager使用静态方法从 中检索颜色。静态方法意味着您不能覆盖调用。
  • 颜色存储为私有字段,并且该类只公开受保护的 getter,没有 setter。没有 setter 意味着你不能在外部调用它。

ProgressBarUI用于的实例JProgressBar派生自UIManager( UIManager#getUI),这又是一个静态方法。

这让我们没有那么多选择。我认为可行的JProgressBar#setUI方法是使用以下方法:

  • 这允许您创建自己的 UI 实例
  • 这允许覆盖受保护的吸气剂

这种方法的主要缺点是它要求您预先知道您的应用程序将使用哪种外观。例如,如果应用程序使用 Metal,这将变成

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 );
Run Code Online (Sandbox Code Playgroud)

由于必须预先了解外观的主要缺点,因此对该解决方案并非 100% 满意。