Search code examples
javainputjtextfieldbufferedreaderkeylistener

How to use a JTextPanel to get a string


I need to get an input from keyboard using a JtextPanel, saving it on a string when I press enter, then use that string to do some action based on line given in input ( example "help" or "quit"). I got this in my KeyListener for JTextPanel:

...
public void keyPressed(KeyEvent e) {
     int key = e.getKeyCode();    

     if (key == KeyEvent.VK_ENTER) {
        inputString = textField.getText();
        textArea.append(inputString + "\n");
        textField.setText("");

        }
}
....

, but I cant call this method directly. I would need something like

String input = processInput();
    if((input).equals("help"))
          ............
    else if ((input).equals("go"))
          ............

and processInput should be a method that waits for the (key== KeyEvent.VK_ENTER), like happens when you use the scanf in C or the bufferedReader in java, it waits for you giving a string from keyboard till you press enter. EDIT

My app manages commands like that

while(!finished) {

    finished = processInput() 
}

processInput manages the command given in input. That's why I cant call processInput() from the keyListener I hope i was clear, my english is so bad!

thanks


Solution

  • How about this approach, pretty simple.

    KeyListener:

    ...
    public void keyPressed(KeyEvent e) {
         int key = e.getKeyCode();    
    
         if (key == KeyEvent.VK_ENTER) {
            inputString = textField.getText();
            textArea.append(inputString + "\n");
            textField.setText("");
            processInput(inputString); //crunch it
            }
    }
    ....
    

    And elsewhere

    public void processInput(String input) {
        if((input).equals("help"))
              ............
        else if ((input).equals("go"))
              ............
    }