swing快速入门(三十九)进度对话框

注释很详细,直接上代码

上一篇

新增内容
1.模拟耗时操作
2.使用计时器更新进度对话框

源码:

package swing31_40;

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

public class swing_test_37 {

    //定义一个计时器
    //为什么定义在这里而不是在使用时定义?
    //因为在new时定义会导致timer.stop();这句报错未初始化
    Timer timer;

    //初始化方法
    public void init(){
        //模拟耗时操作
        final SimulatedActivity simulatedActivity = new SimulatedActivity(100);

        //启动耗时操作线程
        final Thread targetThread= new Thread(simulatedActivity);

        //启动线程
        targetThread.start();

        //创建进度条对话框
        ProgressMonitor dialog = new ProgressMonitor(null, "等待任务完成", "已完成:", 0, simulatedActivity.getAmount());

        //设置定时器(300毫秒执行一次)
        timer = new Timer(300, new ActionListener() {
            //定时器执行事件
            @Override
            public void actionPerformed(ActionEvent e) {

                //设置对话框进度条
                dialog.setProgress(simulatedActivity.getCurrent());

                //如果进度条已完成,则停止计时器
                if (dialog.isCanceled()){

                    timer.stop();//停止计时器
                    targetThread.interrupt();//中断线程
                    System.exit(0);//退出程序

                }
            }
        });

        timer.start();//启动计时器

    }

    public static void main(String[] args) {
        //启动程序
        new swing_test_37().init();
    }

    //定义一个线程任务,模拟耗时操作
    private class SimulatedActivity implements Runnable{

        //设置内存可见
        private volatile int current = 0;
        private int amount;//总量

        //构造方法
        public SimulatedActivity(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;
        }

        //重写run方法
        @Override
        public void run() {

            //通过循环,不断的修改current的值,模拟任务完成量
            while(current<amount){
                try {
                    //睡眠50毫秒
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    //中断异常处理
                    e.printStackTrace();
                }
                current++;//增加当前值
            }
        }
    }

}

️效果演示:

swing快速入门(三十九)进度对话框_第1张图片
下一篇

你可能感兴趣的:(#,Swing,java,swing)