Mohit Deshpande
Mohit Deshpande

Reputation: 55217

Unix less-like terminal scrolling in Java

By default, if lots of text is outputted, the terminal scrolls down to the very last line and then the user has to scroll all the way up to read from the top. I want a Java-like way to implement the scrolling offered in the Unix "less" program. I would like a way to output lots of text and the user be able to start at the top and scroll down at their pace.

Upvotes: 0

Views: 637

Answers (1)

mw4rf
mw4rf

Reputation: 26

That's not a Less implementation, but here's an idea :

  • Split your output in several parts : very long String => array of short Strings (~10-15 lines) ;
  • Make a loop, waiting for user input to display the next iteration
String s = "blahhh foo.... I'm a very long string, with long lines and
a lot of linebreaks...";

String[] looping = s.split("\n"); // whatever delimiter you need

for(int i = 0 ; i < looping.length ; i++) {
  // print 
  System.out.print(looping[i]);

  // wait for user input
  Scanner scanner = new Scanner(System.in);
  String a =  scanner.nextLine(); 

  // assigne a key to stop the loop before the end
  if(a.equalsIgnoreCase("X") // X, or whatever you want
  break;
}

Upvotes: 1

Related Questions