KeyEvent issue on JTextArea

五迷三道 提交于 2019-12-11 03:26:24

问题


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);
     }
}

回答1:


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.




回答2:


When you have input of one single line of any length, you should consider using JTextField.

Ideally, JTextArea can be used for accepting multiline input.



来源:https://stackoverflow.com/questions/14055039/keyevent-issue-on-jtextarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!