Now, I have this text UI progress bar for terminals that looks like:
[##########################################################################....]
Code
package io.github.coderodde.textui.components;
/**
* This class implements a simple text UI progress bar.
*/
public class TextProgressBar {
private float progress = 0.0f;
private final int width;
private boolean printedOnce = false;
public TextProgressBar(int width) {
this.width = checkWidth(width);
}
public void print() {
if (printedOnce) {
clearBar();
} else {
printedOnce = true;
}
System.out.print(getBar());
System.out.flush();
}
public void inc(float dx) {
progress += dx;
progress = (float) Math.max(0.0, Math.min(1.0, progress));
}
private void clearBar() {
for (int i = 0; i < width + 2; ++i) {
System.out.print("\b");
}
}
public static void main(String[] args) {
TextProgressBar bar = new TextProgressBar(78);
for (float f = 0.0f; f <= 1.005f; f += 0.01f) {
bar.print();
bar.inc(0.01f);
try {
Thread.sleep(100L);
} catch (InterruptedException ignored) {
}
}
}
private String getBar() {
int nFilled = (int)(progress * width);
int nNonFilled = width - nFilled;
StringBuilder sb = new StringBuilder(width + 2).append("[");
for (int i = 0; i < nFilled; ++i) {
sb.append("#");
}
for (int i = 0; i < nNonFilled; ++i) {
sb.append(".");
}
return sb.append("]").toString();
}
private static int checkWidth(int width) {
if (width < 1) {
throw new IllegalArgumentException(
String.format("width (%d) < 1", width));
}
return width;
}
}
Critique request
Please, tell me anything that comes to mind.
NB
NetBeans refused to erase the previous progress bar on the same line, so it doesn't work in all environments.
bar.setProgress(f)would seem more sensible thanbar.inc(0.1f)- do not get the two loop counters out of sync \$\endgroup\$StringBuilderreuse worth a try? The class is IO-bound and is already thread-unsafe, so it should not break anything. On the other hand, we should try to avoid unnecessary state. \$\endgroup\$InterruptedException. This is a demo, yes, but throwing it frommain()is even shorter. \$\endgroup\$