java swing中耗时任务进度监控-胶囊进度条

在实际应用中,有时我们需要通过进度条模拟耗时任务的运行状态,这时进度条就会很有用。

以下为用JProgressBar实现的进度条模拟耗时任务的实现:

import javax.swing.*;
import java.awt.*;

public class CustomProgressBar extends JProgressBar {
    public CustomProgressBar() {
        super(0, 100);
        setStringPainted(true); // 启用字符串绘制
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        String text = getString();
        if (text != null) {
            // 获取进度条的宽度和高度
            int width = getWidth();
            int height = getHeight();
            // 设置文本的左对齐位置
            FontMetrics metrics = g.getFontMetrics(getFont());
            int textWidth = metrics.stringWidth(text);
            int x = 5; // 在左侧留一些边距
            int y = (height + metrics.getAscent()) / 2 - metrics.getDescent();
            // 清除之前的文本
            g.setColor(getBackground());
            g.fillRect(0, 0, width, height); // 清除整个进度条区域

            // 绘制文本
            g.setColor(getForeground()); // 设置文本颜色
            g.drawString(text, x, y); // 绘制文本
        }
    }

}
import cn.hutool.core.util.StrUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.RoundRectangle2D;

public class ScrollingTextProgressBar extends JFrame {
    private JProgressBar progressBar;
    private Timer timer;
    private String scrollingText;
    private int textPosition = 0;

    public ScrollingTextProgressBar() {
        setSize(400, 60);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setUndecorated(true);
        setAlwaysOnTop(true);
        int radius = 60; // 圆角半径
        setShape(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), radius, radius));
        progressBar = new CustomProgressBar();
        progressBar.setStringPainted(true);

        progressBar.setString("");
        progressBar.setBackground(new Color(65, 164, 72));
        progressBar.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 20));
        progressBar.setForeground(Color.WHITE);

        setLayout(new BorderLayout());
        add(progressBar, BorderLayout.CENTER);
        startLongRunningTask();

    }

    private void startLongRunningTask() {
        // 重置进度条
        progressBar.setString("");
        textPosition = 0;

        // 创建定时器来更新进度条
        timer = new Timer(500, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                    updateProgressBarString();
            }
        });
        timer.start(); // 启动定时器
    }

    private void updateProgressBarString() {
        // 创建滚动字符串
        String displayText = StrUtil.repeat(" ",textPosition) + scrollingText;
        if(scrollingText.length() > 50) {
            displayText = displayText.substring(textPosition, textPosition + 50); // 限制显示的长度
        }
        progressBar.setString(displayText);
        // 更新文本位置
        textPosition+=5;
        if (textPosition >= 50) {
            textPosition = 0;
            scrollingText = scrollingText.replaceAll("^\\s+", "");
        }
    }

    public void setScrollingText(String text){
        this.scrollingText = text;
    }

    public void stopScroll(){
        timer.stop();
        dispose();
        System.exit(0);
    }

}
import javax.swing.*;

public class TestWasteTimeTask {
    ScrollingTextProgressBar example;

    public void doTask() throws InterruptedException {
        example = new ScrollingTextProgressBar();
        example.setScrollingText("正在运行,请耐心等待...");
        example.setVisible(true);
        for (int i = 0; i <= 100; i++) {
            Thread.sleep(50); // 模拟耗时任务
            System.out.println("=========task"+i);

        }
    }

    private void startLongRunningTask() {
        // 使用SwingWorker来执行耗时任务
        SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {
            @Override
            protected Void doInBackground() throws Exception {
                doTask();
                return null;
            }

            @Override
            protected void process(java.util.List<Integer> chunks) {

            }

            @Override
            protected void done() {
                example.stopScroll();
            }
        };

        worker.execute(); // 启动工作线程
    }



    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            TestWasteTimeTask testWasteTimeTask = new TestWasteTimeTask();
            testWasteTimeTask.startLongRunningTask();
        });
    }

}

模拟进度条:

以上程序也可以根据情况进行扩展,引入线程等效果更佳!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值