java swing 使用JProgressMonitor 创建进度条

package zikao.swing;

import javax.swing.*;


public class ProgressMonitorTest {
    /*
    ProgressMonitor的用法与ProgressBar相似 , ProgressMonitor可以直接创建一个进度对话框

    提供的构造方法:

    public ProgressMonitor(Component parentComponent,Object message,String note,
    int min,int max):

    parentComponent: 对话框的父组件

    message: 对话框的描述信息

    note: 进度的提示信息

    min: 进度条的最小值

    max: 进度条的最大值

     */

    Timer timer;
    public void init() {
        ProgressMonitor monitor = new ProgressMonitor(null, "等待任务完成", "已完成", 0, 100);

        SimulaterActivity simulaterActivity = new SimulaterActivity(100);
        new Thread(simulaterActivity).start();

        //设置定时任务

        timer = new Timer(100, e -> {
            //读取当前任务量,修改进度
            int current = simulaterActivity.getCurrent();
            monitor.setProgress(current);
            //判断用户是否点击了取消按钮,停止定时任务,关闭对话框,退出程序
            if (monitor.isCanceled()) {
                timer.stop();
                monitor.close();
                System.exit(0);
            }
            if (current==100){
                timer.stop();
                System.exit(0);
            }
        });
        timer.start();
    }
    //定义线程任务,模拟相关任务

    private static class SimulaterActivity implements Runnable {
        //内存可见
        private volatile int current = 0;
        private int amount;

        public SimulaterActivity(int amount) {
            this.amount = amount;
        }

        public int getCurrent() {
            return current;
        }

        public void setCurrent(int current) {
            this.current = current;
        }

        public int getAmount() {
            return amount;
        }

        public void setAmount(int amount) {
            this.amount = amount;
        }

        @Override
        public void run() {
            //通过循环,不断的修改current的值,模拟任务我完成量
            while (current < amount) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                current++;
            }
        }
    }

    public static void main(String[] args) {
        new ProgressMonitorTest().init();
    }
}

                                                            程序效果,请看评论区b站链接

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值