• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 261
  • Last Modified:

GUI Enter Key Listener

I'm having issues with my first GUI program.  I have a JTextArea set up for input and it's giving me problems.  I've tried a few methods for getting the input and it seems to lock up the computer.

Here is the problem piece of code:

Message is a JLabel and text is a JTextArea.  This is inside an actionPerformed method for the class.  action = e.getActionCommand();

        else if(action.equals("search(int)")) {
          message.setText("Enter the value to search for:");
          while(inputtedText == null) {}
          try {
            String str = " ";
            int val = Integer.parseInt(inputtedText);
            input.setText(" ");
            inputtedText = null;
            if (list.search(val))
              text.append("\n" + val + " was found in the list.");
              text.append("\n" + val + " was not found in the list.");
          catch(Exception e) {
            text.append("\nInput error. Please try the method again.");

Here is a KeyListener I set up to complement this:

    private class TextListener implements KeyListener {
      public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == e.VK_ENTER);
      public void keyTyped(KeyEvent e) {}
      public void keyReleased(KeyEvent e) {}
      public void returnInput() {
        inputtedText = input.getText();

Essentially, I want to do this within the actionPerformed:
-Change the message to prompt for input
-wait for input
-read the input from the user after they have pushed the ENTER key.
-pass the input to the search() method

Any help here would be hot.
  • 3
  • 2
1 Solution
you can't wait for input in your actionPerformed(), thats what is blocking your gui.

Instead add an action listener to your text field. It will then get called when the user hits enter
rkjohnson2005Author Commented:
Is there a way to define the action listener on the text field so that it knows which method (in this case "search(int)") was just called?
No, you'll need to set some flag in your class to mark that.
(Or I guess you could check the label as that currently gets set)
rkjohnson2005Author Commented:
OK. I got it to work now. Thanks.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now