Press Up Arrow and Brings the Last Java Console Command

4k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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/

3
On

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
}