user3369353
user3369353

Reputation: 1

Appending a char using KeyEvent ( KeyPressed , KeyTyped ,...) to a JTextArea

when i try to append a char or string to jtextarea after pressing a Specific button , something odd happens , e.g i want to append the '}' after pressing '{' by user in jtextarea , by the following code , the final string in jTextArea would be "}{" instead of being "{}"

private void keyPressedEvent(java.awt.event.KeyEvent evt)
{
    if(evt.getkeychar() == '{' )
    {
        JtextArea1.append("}");
    }
}

Upvotes: 0

Views: 490

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

You should almost never use a KeyListener on a JTextArea or other JTextComponent. For this, I'd use a DocumentFilter which allows you to update the Document before the user's input has been sent to it.

e.g.,

import javax.swing.*;
import javax.swing.text.*;

public class DocFilterEg {
   public static void main(String[] args) {
      JTextArea textArea = new JTextArea(10, 20);
      PlainDocument doc = (PlainDocument) textArea.getDocument();
      doc.setDocumentFilter(new DocumentFilter() {
         @Override
         public void insertString(FilterBypass fb, int offset, String text,
               AttributeSet attr) throws BadLocationException {
            text = checkTextForParenthesis(text);
            super.insertString(fb, offset, text, attr);
         }

         @Override
         public void replace(FilterBypass fb, int offset, int length,
               String text, AttributeSet attrs) throws BadLocationException {
            text = checkTextForParenthesis(text);
            super.replace(fb, offset, length, text, attrs);
         }

         private String checkTextForParenthesis(String text) {
            if (text.contains("{") && !text.contains("}")) {
               int index = text.indexOf("{") + 1; 
               text = text.substring(0, index) + "}" + text.substring(index);
            }
            return text;
         }
      });
      JOptionPane.showMessageDialog(null, new JScrollPane(textArea));
   }
}

Upvotes: 4

Related Questions