Search code examples
javaconsole-applicationarrow-keys

Press Up Arrow and Brings the Last Java Console Command


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.


Solution

  • 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/