swing快速入门(三十九)进度对话框
2024-01-09 19:38:35
    		🎁注释很详细,直接上代码
🧧新增内容
🧨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++;//增加当前值
            }
        }
    }
}
🎗?效果演示:
    			文章来源:https://blog.csdn.net/m0_73756108/article/details/135393215
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
    	本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
