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

Answers


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.


Need Your Help

bash - extract number from string

regex bash

I want to extract a number of variable length from a string.

PNG Compression

image optimization png

Some PNG images although just 150px x 160px wide have 60KB filesize. I've already run them though optimizers (ImageOptim for Mac) but that didn't help much.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.