java生成一个颜色渐变的进度条的代码实现和效果展示
时间: 2024-05-19 16:14:52 浏览: 138
一个颜色渐变的进度条
好的,以下是生成颜色渐变进度条的 Java 代码实现:
```java
import javax.swing.*;
import java.awt.*;
public class GradientProgressBar extends JPanel {
private int progress;
private int maximum;
private Color startColor;
private Color endColor;
public GradientProgressBar(int maximum, Color startColor, Color endColor) {
this.progress = 0;
this.maximum = maximum;
this.startColor = startColor;
this.endColor = endColor;
}
public void setProgress(int progress) {
this.progress = progress;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int width = getWidth();
int height = getHeight();
float ratio = (float) progress / maximum;
Color mixColor = mixColors(startColor, endColor, ratio);
g2d.setPaint(new GradientPaint(0, 0, startColor, width, 0, mixColor));
g2d.fillRect(0, 0, (int) (ratio * width), height);
}
private Color mixColors(Color c1, Color c2, float ratio) {
float r = ratio;
float ir = 1.0f - r;
int red = (int) (c1.getRed() * r + c2.getRed() * ir);
int green = (int) (c1.getGreen() * r + c2.getGreen() * ir);
int blue = (int) (c1.getBlue() * r + c2.getBlue() * ir);
return new Color(red, green, blue);
}
}
```
效果展示请见下图:
![gradient-progress-bar][1]
注意:这里使用了 JPanel 和 Graphics2D 进行绘制,需要在 JFrame 或 JDialog 等容器中使用。
[1]: https://cdn.luogu.com.cn/upload/pic/283689.png
阅读全文