在swing中,大部分控件都丑的不行,进度条控件jprogressbar,这个还算说得过去,就是默认颜色不咋的好看。
今天的优化,还是一贯的风格,简单大方就好,先来张图片感受一下
上图中,分别有背景色和前景色,这个设置起来很容易,有现成的API,直接setBackground和setForeground,我们来测试一下
jProgressBar.setBackground(new Color(209, 206, 200));// 背景色
jProgressBar.setForeground(new Color(172, 168, 163));// 前景色(进度条的颜色)
效果图:
大家注意到我红色框中的内容,就是进度条的数值,这个不管我们的back和fore设置什么颜色,它都很坚决的是白色,铁打不变风吹不动,老实说白色也不算丑,但是在我们做全局性优化时,就显得与整体颜色不匹配了,看了一圈代码,发现他并没有提供直接修改这个颜色的API,查阅资料发现这个颜色需要在UI类中修改。
在BasicProgressBarUI中,最上面有两个变量:selectionForeground、selectionBackground
public class BasicProgressBarUI extends ProgressBarUI {
private int cachedPercent;
private int cellLength, cellSpacing;
// The "selectionForeground" is the color of the text when it is painted
// over a filled area of the progress bar. The "selectionBackground"
// is for the text over the unfilled progress bar area.
private Color selectionForeground, selectionBackground;
...... // 代码省略
}
注释写的还是很清楚的,就是控制这个数值颜色的,在installDefaults方法中,可以看到给它赋的颜色值
protected void installDefaults() {
LookAndFeel.installProperty(progressBar, "opaque", Boolean.TRUE);
LookAndFeel.installBorder(progressBar,"ProgressBar.border");
LookAndFeel.installColorsAndFont(progressBar,
"ProgressBar.background",
"ProgressBar.foreground",
"ProgressBar.font");
cellLength = UIManager.getInt("ProgressBar.cellLength");
if (cellLength == 0) cellLength = 1;
cellSpacing = UIManager.getInt("ProgressBar.cellSpacing");
// 就是下面这两个了,这个就是默认的颜色
selectionForeground = UIManager.getColor("ProgressBar.selectionForeground");
selectionBackground = UIManager.getColor("ProgressBar.selectionBackground");
}
既然找到地方了,那我们就把这两个值修改成我们自己想要的,不过要注意的是,这两个值是私有的,也没有提供set方法,震惊之余,发现它还是有一个get方法的,那我们就只能重写它的这两个get方法了。
package com.wolffy.ui;
import javax.swing.plaf.basic.BasicProgressBarUI;
import java.awt.Color;
/**
* Created by SongFei on 2017/11/17.
*/
public class MyProgressBarUI extends BasicProgressBarUI {
// 滚动条覆盖前的字体颜色
@Override
protected Color getSelectionBackground() {
return Color.BLUE;
}
// 滚动条覆盖后的字体颜色
@Override
protected Color getSelectionForeground() {
return Color.RED;
}
}
覆盖前:
覆盖后:
为了颜色区分的明显,我这里选了蓝色和红色,大家可以根据自己需要来调整相应的颜色!
好了,基本上就这些了,主要就是这个颜色的更换,还有边框颜色,这个也是有现成的API,这里就不再多说!