Last active
May 21, 2019 01:00
-
-
Save simonwep/a9ca8d4f3ef3d5c412bbd931b0574e91 to your computer and use it in GitHub Desktop.
An simple console progressbar with message and a indicator.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package classes; | |
public class ConsoleProgressBar { | |
private double minValue; | |
private double maxValue; | |
private int barSize; | |
private int barPos; | |
private char[] loading = {'|', '\\', '-', '/'}; | |
private int loadingIndex = 0; | |
private String infoText = ""; | |
/** | |
* Create an new console-progressbar | |
* | |
* @param minValue Minumum from the number-range | |
* @param endValue Maximum from the number-range | |
* @param barLength The length of the bar (characters) | |
*/ | |
public ConsoleProgressBar(double minValue, double endValue, int barLength) { | |
this.minValue = minValue; | |
this.maxValue = endValue; | |
this.barSize = barLength; | |
} | |
/** | |
* Update the progressbar and print it. | |
* | |
* @param msg The new message. | |
* @return This ConsoleProgressBar instance. | |
*/ | |
public ConsoleProgressBar update(String msg) { | |
update(maxValue + 1, msg); | |
return this; | |
} | |
/** | |
* Update the progressbar and print it. | |
* | |
* @param newVal The new value. | |
* @return This ConsoleProgressBar instance. | |
*/ | |
public ConsoleProgressBar update(double newVal) { | |
update(newVal, null); | |
return this; | |
} | |
/** | |
* Update the progressbar and print it. | |
* | |
* @param newVal The new value. | |
* @param msg The new message. | |
* @return This ConsoleProgressBar instance. | |
*/ | |
public ConsoleProgressBar update(double newVal, String msg) { | |
if (newVal < maxValue) | |
barPos = (int) Math.ceil(map(newVal, minValue, maxValue, 0, barSize)); | |
if (msg != null) | |
this.infoText = msg; | |
print(); | |
return this; | |
} | |
/** | |
* Print the progressbar manually | |
*/ | |
public void print() { | |
if (loadingIndex++ == loading.length - 1) | |
loadingIndex = 0; | |
char inde = barPos == barSize ? '-' : loading[loadingIndex]; | |
String prog = repeate(barPos, '#'); | |
String pla = repeate((barSize - barPos), '-'); | |
System.out.print("\r" + prog + pla + " " + inde + " " + infoText); | |
System.out.flush(); | |
} | |
// Map number ranges | |
private double map(double value, double as, double ae, int bs, int be) { | |
return (value - as) * ((double) (be - bs) / (ae - as)); | |
} | |
// Repeat an character n-times | |
private String repeate(int n, char c) { | |
if (n <= 0) | |
return ""; | |
StringBuilder sb = new StringBuilder(); | |
for (int j = 0; j < n; j++) | |
sb.append(c); | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment