java生成一个颜色渐变的进度条的代码实现
时间: 2024-05-14 09:13:04 浏览: 92
以下是一个简单的Java代码实现颜色渐变的进度条:
```
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class GradientProgressBar extends JPanel {
private int progress;
public GradientProgressBar() {
this.setPreferredSize(new Dimension(200, 20));
this.progress = 0;
}
public void setProgress(int progress) {
this.progress = progress;
this.repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int width = this.getWidth() - 1;
int height = this.getHeight() - 1;
// 绘制外边框
g.setColor(Color.BLACK);
g.drawRect(0, 0, width, height);
// 绘制进度条背景色
g.setColor(new Color(255, 255, 255));
g.fillRect(1, 1, width - 2, height - 2);
// 计算进度条渐变色
Color startColor = new Color(0, 255, 0);
Color endColor = new Color(255, 0, 0);
float ratio = (float)this.progress / (float)100;
int red = (int)(endColor.getRed() * ratio + startColor.getRed() * (1 - ratio));
int green = (int)(endColor.getGreen() * ratio + startColor.getGreen() * (1 - ratio));
int blue = (int)(endColor.getBlue() * ratio + startColor.getBlue() * (1 - ratio));
Color progressColor = new Color(red, green, blue);
// 绘制进度条渐变色
g.setColor(progressColor);
int progressWidth = (int)((float)(width - 2) * ratio);
g.fillRect(1, 1, progressWidth, height - 2);
}
}
```
当然,具体的实现方式还要根据具体需求来做相应的调整。
阅读全文