Search code examples
javaswingjtextareajtextpanekeyevent

KeyEvent issue on JTextArea


I am new to GUI programming. While practicing KeyEvent handling on Java Swing JTextarea I face one problem. The listener interface is implemented by text area itself.

When I pressed VK_ENTER key in text area I get text from text area then I displayed that text into JTextPane. After that I set text as empty string on text area. Here I used keyPressed key event - it is creating one new line in text area but already I set text area row as 0 (zero).

Actually I want one row in text area I don't want two line in text area, How to resolve this problem?

This is my code:

public void keyPressed(KeyEvent evt) {

   try {
       if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
           if (evt.isShiftDown()) {  
              textArea .setText(textArea.getText() + "\n");
           } else {   
                inputMsg = textArea.getText().trim();
                textArea.setText(EMPTYSTRING);
                if (!inputMsg.equals(EMPTYSTRING)) {   
                   textPane.setText(inputMsg);
                }
                textArea.requestFocus();
              }
          }
     } catch (Exception ex) {
         logger.log(Level.SEVERE, "Exception in textArea.keyReleased() : ", ex);
     }
}

Solution

  • Actually I want one row in textarea I don't want two line in textarea, How to resolve this problem?

    then why are you using textarea?, use JTextField

    EDIT after asker's comments:

    The additional new line is coming as you are providing your logic in keyPressed method. When you release the key, the ENTER makes it effect on the text area (by adding new line for ENTER).

    You can try your logic in public void keyReleased(java.awt.event.KeyEvent evt) method instead and it should work.

    Other way could be to consume the released event in pressed event after your logic, but I'm not sure how.