简体   繁体   中英

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 , eg 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("}");
    }
}

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.

eg,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM