首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >设置JProgressBar文本颜色

设置JProgressBar文本颜色
EN

Stack Overflow用户
提问于 2015-02-04 22:44:14
回答 2查看 2.2K关注 0票数 3

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

我读到您可以使用UIManager来设置JProgressBars的全局颜色,但我只想为这个(和另一个,但这无关紧要)这样做。

我还读到了HERE,我唯一的其他选择就是修改JProgressBar类。我该怎么做呢?

EN

回答 2

Stack Overflow用户

发布于 2015-02-04 23:04:53

看一下源代码,这并不容易。

颜色存储在BasicProgressBarUI类中:

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

用于JProgressBarProgressBarUI实例派生自UIManager (UIManager#getUI),这也是一个静态方法。

这就给我们留下了不多的选择。我认为一个可行的方法是使用JProgressBar#setUI方法:

这允许您创建自己的UI instance

  • This允许覆盖受保护的

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

代码语言:javascript
复制
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 );

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

票数 5
EN

Stack Overflow用户

发布于 2015-02-04 22:52:34

您可以将setStringPainted属性设置为true:

代码语言:javascript
复制
progressBar.setStringPainted(true);
progressBar.setForeground(Color.blue);
progressBar.setString("10%");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28324155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档