2

I need to create something like a progress bar with java that appear on the output terminal of Netbeans. My idea is to have on the output :

loading *

with the asterisk that seems like something that spin by using the sequence of - \ | / -. I have thought to this code :

public void progressBar(int min){ //minute of spin 
    long time=System.currentTimeMillis();
    long check_time;
    int i=1;
    while(check_time-time<min){
        switch(i){
            case 1:
                System.out.println("loading -");
                i++;
            case 2:
                System.out.println("loading \");
                i++;
            case 3:
                System.out.println("loading |");
                i++;
            case 4:
                System.out.println("loading /");
                i=1;
        }
        check_time=System.currentTimeMillis();
    }
}

but the output of this code is :

loading -
loading \
loading |
loading /
// and so on 

I would that "loading" isn't written continuously and the following symbol appear in sequence to seems like a wheel that rotate.

  • 2
    You could take advantage of `\r` which allows you to move the caret and overwrite existing text but its support really depends on the terminal you are using to show the progress bar. In any case there's no need to reinvent the wheel: https://github.com/ctongfei/progressbar – Jack Nov 06 '17 at 21:51
  • See http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html#progress-indicator for some more fancy ways to do progress indicators using ANSI escape codes. – michid Nov 06 '17 at 22:02
  • thanks @michid for the help this website is full of good content . – riccardo_castellano Nov 07 '17 at 01:25

1 Answers1

3

The following works in my Windows Command Prompt, but it doesn't work inside Eclipse, since Eclipse treats \r as a full \r\n. Don't know if it works in NetBeans or on Linux.

String spin = "-\\|/";
for (int i = 0; i < 50; i++) {
    System.out.print("loading " + spin.charAt(i % 4) + "\r");
    System.out.flush();
    Thread.sleep(100);
}

The code will spin for 5 seconds.

Andreas
  • 154,647
  • 11
  • 152
  • 247