Java implements progress bar loading effect

Table of contents

Preface

1. Java Swing implementation

2. Java for loop traversal implementation


Preface

        Progress bars are already very common in the software we use daily, but apart from installing or updating software, they are usually only seen on web pages. This article would like to share how to use Java code to achieve the effect of progress bar loading.


1. Java Swing implementation

Swing  can be used to make loading progress bars for some pages, which is very good and has a beautiful effect. The configuration can also be adjusted according to your own needs.

Code: 

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

/**
 * 加载进度条
 */
public class StartLoadingView extends JWindow implements Runnable {

    /*** 定义加载窗口大小*/
    public static final int LOAD_WIDTH = 1075;// 页面宽度
    public static final int LOAD_HEIGHT = 604;// 页面高度

    /*** 获取屏幕窗口大小*/
    public static final int WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width;
    public static final int HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height;

    /*** 定义进度条组件*/
    public JProgressBar progressbar;

    /*** 定义标签组件*/
    public JLabel label;

    // 构造函数
    public StartLoadingView() {

        // 创建标签,并在标签上放置一张背景图
        label = new JLabel(new ImageIcon("C:\\Users\\admin\\Desktop\\java.jpg"));// 这里放页面要展示的背景图
        label.setBounds(0, 0, LOAD_WIDTH, LOAD_HEIGHT - 15);
        // 创建进度条
        progressbar = new JProgressBar();
        // 显示当前进度值信息
        progressbar.setStringPainted(true);
        // 设置进度条边框不显示
        progressbar.setBorderPainted(false);
        // 设置进度条已加载的背景色
        progressbar.setForeground(new Color(210, 0, 80, 255));
        // 设置进度条未加载的背景色
        progressbar.setBackground(new Color(188, 190, 194));
        progressbar.setBounds(0, LOAD_HEIGHT - 15, LOAD_WIDTH, 15);
        // 添加组件
        this.add(label);
        this.add(progressbar);
        // 设置布局为空
        this.setLayout(null);
        // 设置窗口初始位置
        this.setLocation((WIDTH - LOAD_WIDTH) / 2, (HEIGHT - LOAD_HEIGHT) / 2);
        // 设置窗口大小
        this.setSize(LOAD_WIDTH, LOAD_HEIGHT);
        // 设置窗口显示
        this.setVisible(true);
    }

    public static void main(String[] args) {
        StartLoadingView t = new StartLoadingView();
        new Thread(t).start();
    }

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            try {
                // 加载进度条需要用到多少秒,20就是2秒
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            progressbar.setValue(i);
        }
        JOptionPane.showMessageDialog(this, "程序加载成功");
        this.dispose();
        // 如果这里不继续执行代码,将关闭本次运行
    }

}

2. Java for loop traversal implementation

    public static void main(String[] args) {
        char incomplete = '░'; // U+2591 Unicode Character 表示还没有完成的部分
        char complete = '█'; // U+2588 Unicode Character 表示已经完成的部分
        int total = 100;
        StringBuilder builder = new StringBuilder();
        Stream.generate(() -> incomplete).limit(total).forEach(builder::append);
        for (int i = 0; i < total; i++) {
            builder.replace(i, i + 1, String.valueOf(complete));
            String progressBar = "\r" + builder;
            String percent = " " + (i + 1) + "%";
            System.out.print(progressBar + percent);
            try {
                // 这里为了表示越到后面越慢的场景,所以这里的sleep不是一个固定的数值。
                Thread.sleep(i * 5L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

1. First, create the unfinished part through Stream.generate() . Here, StringBuilder is used to create a string object and filled in through the append method, as follows: Stream.generate(() -> incomplete).limit(total).forEach (builder::append);

2.  Set total to 100 and limit the length. Then use a for loop to continuously replace the unfinished parts and replace the characters one by one with the completed characters, builder.replace(i, i + 1, String.valueOf(complete)) .

PS . Here are three things you need:

  • The progress bar is always displayed on one line without changing numbers, so we have to use  the System.out.print() method to output, not the System.out.println(); method; if we directly use the System.out.print() ); If you output, you will find that although it appears on the same line, it will become longer and longer, and the string of each loop will be connected at the end, which is not possible. So here we need to use the carriage return symbol. Everyone knows that \r\n is used for carriage return and line feed. In fact, these two symbols \r is a carriage return and \n is a line feed. Enter moves the cursor to the beginning of the line, and line feed moves the cursor to the next line.
  • The progress bar will slowly change according to the network and resource package size when downloading, so we need to have a certain speed and cannot complete it all at once. Here we can simply implement it through Thread.sleep( ) ;

If this article is helpful or inspiring to you, please click three links: Like, Comment, Collection➕Follow. Your support is my biggest motivation to keep writing. 

Guess you like

Origin blog.csdn.net/weixin_42555014/article/details/133376030