我有一个名为 playerhealth 的 JProgressBar。我将条形颜色设置为绿色。这使得文本很难看清,所以我想将 JProgressBar 中的文本颜色设置为黑色。
我读到您可以使用 UIManager 来设置 JProgressBars 的全局颜色,但我只想为这个(和另一个,但这并不重要)这样做。
我还读了HERE我唯一的其他选择是更改 JProgressBar 类。我该怎么做?
最佳答案
查看源代码,这并不容易。
颜色存储在 BasicProgressBarUI
类中:
- 在构造函数中,使用静态方法从
UIManager
中检索颜色。静态方法意味着您无法覆盖调用。 - 颜色存储为私有(private)字段,该类仅公开 protected getter,不公开 setter。没有 setter 意味着您不能从外部调用它。
用于 JProgressBar
的 ProgressBarUI
实例派生自 UIManager
(UIManager#getUI
) ,这又是一个静态方法。
这让我们没有太多选择。我认为可行的方法是使用 JProgressBar#setUI
方法:
- 这允许您创建自己的 UI 实例
- 这允许覆盖 protected 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% 满意。
关于java - 设置 JProgressBar 文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28324155/