【问题标题】:Set JProgressBar TEXT color设置 JProgressBar TEXT 颜色
【发布时间】:2015-04-04 03:19:58
【问题描述】:

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

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

我还阅读了HERE,我唯一的其他选择是更改 JProgressBar 类。我该怎么办?

【问题讨论】:

  • 你必须小心你使用的外观和感觉!(不同的外观意味着不同的反应。在你设置酒吧 StringPainted().. 和 .setForeground(Color.(your choice) if you看不到反应使用 barname.setOpaque(true);

标签: java swing colors jprogressbar


【解决方案1】:

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

颜色存储在BasicProgressBarUI类中:

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

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

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

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

这种方法的主要缺点是它要求您预先知道您的应用程序将使用哪种外观。例如,如果应用程序使用 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 );

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

【讨论】:

  • 我不确定外观和感觉是什么。如果我还没有真正使用它,它会改变什么吗?
  • 无论您是否愿意,您都拥有/使用 LookAndFeel。外观决定了组件的外观
【解决方案2】:

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

progressBar.setStringPainted(true);
progressBar.setForeground(Color.blue);
progressBar.setString("10%");

【讨论】:

  • setStringPainted 属性决定了字符串是否会出现在进度条上,而不是字符串是否被涂上不同的颜色。
猜你喜欢
  • 1970-01-01
  • 2014-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-02
相关资源
最近更新 更多