我正在尝试通过使用自定义 Painter 对象来更改当前 Swing L&F 中进度条的颜色(我目前正在使用 Nimbus),但是在创建这些进度条时有时会坚持其原始颜色(这种变化似乎随机发生)。
我可能遗漏了一些简单的东西,但我很难过,Painter 对象(它是下面的调用)......
import javax.swing.Painter;
import java.awt.*;
public class ProgressPainter implements Painter {
private Color light, dark;
private GradientPaint gradPaint;
public ProgressPainter(Color light, Color dark) {
this.light = light;
this.dark = dark;
}
@Override
public void paint(Graphics2D g, Object c, int w, int h) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gradPaint = new GradientPaint((w / 2.0f), 0, light, (w / 2.0f), (h /2.0f), dark, true);
g.setPaint(gradPaint);
g.fillRect(2, 2, (w - 5), (h - 5));
Color outline = new Color(0, 85, 0);
g.setColor(outline);
g.drawRect(2, 2, (w - 5), (h - 5));
Color trans = new Color(outline.getRed(), outline.getGreen(), outline.getBlue(), 100);
g.setColor(trans);
g.drawRect(1, 1, (w - 3), (h - 3));
}
}
在应用程序启动时调用...
UIManager.put("ProgressBar[Enabled].foregroundPainter", new ProgressPainter(new Color(125, 255, 125), new Color(25, 175, 25)));
UIManager.put("ProgressBar[Enabled+Indeterminate].foregroundPainter", new ProgressPainter(new Color(125, 255, 125), new Color(25, 175, 25)));
然后稍后使用...创建一个简单的 JProgressBar
JProgressBar progBar = new JProgressBar(0, 100);
progBar.setStringPainted(true);
progBar.setBounds(20, 10, 260, 30);
frame.add(progBar);
frame.setVisible(true);