Fortschrittsbalken für die TextKonsole

Hallo!

Ich würde das so machen:
Code:
   package de.tutorials;
   
   /**
    * @author Tom
    * 
    */
   public class ConsoleProgressIndicator {
   
   	int minValue;
   
   	int currentValue;
   
   	int maxValue;
   
   	int maxChars;
   
   	char progressChar = '#';
   
   	int charsPrintedCount;
   
   	public ConsoleProgressIndicator(int maxChars, char progressChar) {
   		this.maxChars = maxChars;
   		this.progressChar = progressChar;
   	}
   
   	/**
   	 * @param args
   	 */
   	public static void main(String[] args) throws Exception {
   		new ConsoleProgressIndicator(40, '#')
 			 .execute(new IRunnableWithConsoleProgressIndicatorSupport() {
   				    public void run(
 						 ConsoleProgressIndicator consoleProgressIndicator) {
 					 int minValue = 0;
 					 int maxValue = 200; // 100, 1000, 50, 20
 					 consoleProgressIndicator.setup(minValue, maxValue);
 					 for (int i = minValue; i < maxValue; i++) {
 						 consoleProgressIndicator.updateProgress(i);
 						 try {
 							 Thread.sleep(10L);
 						 } catch (InterruptedException e) {
 							 e.printStackTrace();
 						 }
   					    }
   					}
   				});
   
   	}
   
   	protected void setup(int minValue, int maxValue) {
   		this.minValue = minValue;
   		this.maxValue = maxValue;
   	}
   
   	private void execute(
 		 IRunnableWithConsoleProgressIndicatorSupport runnableWithConsoleProgressIndicatorSupport) {
   		System.out.print("[");
   		runnableWithConsoleProgressIndicatorSupport.run(this);
   		System.out.println("]");
   	}
   
   	static interface IRunnableWithConsoleProgressIndicatorSupport {
   		void run(ConsoleProgressIndicator consoleProgressIndicator);
   	}
   
	public void updateProgress(int value) {
   		double actualProgressPercentage = (double) value / maxValue;
   
   		int charsToPrint = (int) (actualProgressPercentage * maxChars)
   				- charsPrintedCount;
   
   		if (charsToPrint > 0) {
   			for (int i = 0; i < charsToPrint; i++) {
 				System.out.print(progressChar);
   			}
   			this.charsPrintedCount += charsToPrint;
   		}
   		
   		this.currentValue = value;
   	}
   }

Um die Prozentuale Anzeige an einer fixen Stelle innerhalb der Konsole anzuzeigen musst du entweder ein wenig magie mit den verschiedenen Escape Sequenzen betreiben \r ...etc. Oder du verwendest JCurses:
http://www.tutorials.de/tutorials177095.html&highlight=jcurses

Btw. der Fortschritt einer langlaufenden Aktion liese sich sicherlich auch sehr schön als Aspekt modellieren (Monitoring) ;-)

Gruß Tom
 
Da hat sich Tom aber richtig ins Zeug gelegt :D
Mir ist noch was eingefallen, warum der Cursor mitwandert..
Ich würd mal versuchen die Zeichen nicht einzeln nacheinander auszugeben:
Code:
for (int i = 0; i < 10; i++)
{
.
.
  System.out.print("#");
.
.
}

sondern erst die ganze Zeile zu einem String zusammen zu basteln und die komplett auszugeben..
 
Zurück