Recipe 0.8. Creating a terminal progress bar
Problem
You want to create a progression bar for terminal.
Definition
A progress bar typically communicates the progress of some work by displaying its percentage of completion and possibly a textual display of this percentage.
A progression bar has 2 modes of execution. Depending on the a priori knowledge of the total steps, we have a Determinate mode or an Indeterminate mode.
Solution
We've define an interface ProgressBar that more or less adapt to the javax.swing.JProgressBar. One of the implemented class JProgressBarAdapter is just an adapter of JProgressBar to the ProgressBar interface. The other that interest us is TerminalProgressBar.
Our terminal progression bar is constituted of 2 parts:
- the current processed step (over all steps) found in the Left Margin (LM)
- the Progression Bar (PB) itself
Here is an example in the determinate mode:
// a new determinate progress bar (10 steps maximum) TerminalProgressBar progressBar = TerminalProgressBar.newInstance(0, 10); // set the left space length progressBar.setLeftMarginLength(3); // set the progress bar length progressBar.setBarLength(10); for (int i = 0; i ≤ 10; i++) { progressBar.setValue(i); } // display the following (note that only one // animating line will appear in your terminal) // 0/10 [ ] // 1/10 [= ] // 2/10 [== ] // 3/10 [=== ] // 4/10 [==== ] // 5/10 [===== ] // 6/10 [====== ] // 7/10 [======= ] // 8/10 [======== ] // 9/10 [========= ] // 10/10 [==========]
and an example in the indeterminate mode:
// change the mode progressBar.setIndeterminate(true); // set the period of refreshing the progress bar (2nd part) progressBar.setRefreshBarPeriod(1); for (int i = 0; i ≤ 10; i++) { progressBar.setValue(i); } // notify the progress bar it is the last task progressBar.completed(); progressBar.setValue(10); // display the following (note that only one // animating line will appear in your terminal) // 0 [===== ] // 1 [ ===== ] // 2 [ ===== ] // 3 [ ===== ] // 4 [ ===== ] // 5 [ =====] // 6 [ ===== ] // 7 [ ===== ] // 8 [ ===== ] // 9 [ ===== ] // 10 [==========]
Discussion
See Also
See also their inclusion in MS readers.