zsh_root
2025-01-06 7857a444de69124e9f7fb45f98b0ae818b107f23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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);
        }
    }
}