0

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Mohit Deshpande
  • 53,877
  • 76
  • 193
  • 251
  • What's giving you trouble? Counting the lines? Determining the height of the terminal? Catching all output to STDOUT without missing any? Recognizing cursor keys for scrolling? – Kilian Foth Jun 05 '11 at 15:14
  • I am having problems caching the String to stdout and cutting off the text in respect to the height of the terminal. I also don't know how to set it up so that when the user presses the Down Arrow, the next line should appear, or if he presses the Up Arrow, the previous line should appear – Mohit Deshpande Jun 05 '11 at 15:25
  • I don't think that's possible. I don't even think you can capture a key press from the terminal in Java (for up/down page or line). You need to go for a GUI. – toto2 Jun 05 '11 at 15:39
  • I doubt you can do this in a platform-independent way. Writing a `more`-like program is a lot easier. – Fred Foo Jun 05 '11 at 15:43
  • 1
    A language that doesn’t even allow you to *think* evil thoughts is obviously a good language. Now no one will ever consider evil. How convenient. – tchrist Jun 05 '11 at 18:24

1 Answers1

1

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;
}
mw4rf
  • 26
  • 1