4

Currently I am on a Java project, which is in console driven. I want to realize a feature that when the user press up arrow in the command line of my program, the command line will show the last command that the user has run.

I found something about the keyboard event as below,

public void keyPressed(KeyEvent evt);
public void keyReleased(KeyEvent evt);
public void keyTyped(KeyEvent evt);

However, I just don't know how to bring the command string to the command line. E.g., when the user presses "up", the command should bring back the the last command as a pre-input on the command line.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Noah
  • 63
  • 1
  • 6

2 Answers2

1

Unless an app uses a special API, its console input is at the mercy of the console driver (for a virtual console, the application providing the virtual console). Fortunately there is a project to connect Java to the readline or editline API, which will provide editing facilities including the use of the up arrow to retrieve the previous line. See http://java-readline.sourceforge.net/

Neil
  • 54,642
  • 8
  • 60
  • 72
0

When ever a user executes a command store it in a temporary variable using
public void keyPressed(KeyEvent evt);
and when the user presses the up key display the value in that variable to the screen

example code:

public void executeCommand(String command){
    temp = command;
    // your code
}



public void keyPressed(KeyEvent evt){
    //display the value in the temp variable to screen
}
Alpine
  • 3,838
  • 1
  • 25
  • 18
  • Thank you :-) Yep, I know this and what I want to really know about is how to bring the last command string back to the command line, as a pre-input command, and then when the user press return, it will be executed, just like the linux terminal. – Noah Feb 25 '11 at 19:33
  • You have to save the history yourself, e.g., `List history` and display e.g., `history.get(0)` when the event fires. – Johan Sjöberg Feb 25 '11 at 19:36
  • However, is it still just to print it on the screen, instead of setting it as a pre-input command? I hope it could be like this, after the up arrow is pressed **>>> last command**, then what the user has to do to run the last command is to press return. – Noah Feb 25 '11 at 19:37