package tools;
|
|
import javax.swing.*;
|
import java.awt.*;
|
|
public class CustomProgressBar extends JProgressBar {
|
private Color textColor = Color.BLACK; // 默认文本颜色
|
|
public CustomProgressBar() {
|
super();
|
setStringPainted(true); // 允许显示文本
|
}
|
|
public void setTextColor(Color textColor) {
|
this.textColor = textColor;
|
}
|
|
@Override
|
protected void paintComponent(Graphics g) {
|
// 先调用父类的paintComponent,绘制进度条的背景和前景
|
super.paintComponent(g);
|
|
if (isStringPainted()) {
|
// 获取进度百分比的文本
|
String text = String.format("%d%%", (int)(getPercentComplete() * 100));
|
Graphics2D g2d = (Graphics2D) g;
|
|
// 获取文本区域的矩形区域
|
FontMetrics metrics = g2d.getFontMetrics();
|
int x = (getWidth() - metrics.stringWidth(text)) / 2;
|
int y = (getHeight() + metrics.getAscent()) / 2;
|
|
// 清除文本区域,避免重影
|
g2d.setColor(getBackground()); // 使用背景色来清除区域
|
g2d.fillRect(x, y - metrics.getAscent(), metrics.stringWidth(text), metrics.getHeight());
|
|
// 设置文本颜色和字体
|
g2d.setColor(textColor);
|
g2d.setFont(getFont().deriveFont(Font.BOLD));
|
|
// 绘制文本
|
g2d.drawString(text, x, y);
|
}
|
}
|
}
|