JTextArea updated with DocumentListener

泄露秘密 提交于 2021-01-28 01:21:21

问题


JTextArea area1 = new JTextArea();
JTextArea area2 = new JTextArea();
DocumentListener documentListener = new DocumentListener() {
      public void changedUpdate(DocumentEvent documentEvent) {
        printIt(documentEvent);
      }
      public void insertUpdate(DocumentEvent documentEvent) {
        printIt(documentEvent);
      }
      public void removeUpdate(DocumentEvent documentEvent) {
        printIt(documentEvent);
      }
      private void printIt(DocumentEvent documentEvent) {
        DocumentEvent.EventType type = documentEvent.getType();
        String typeString = null;
        if (type.equals(DocumentEvent.EventType.CHANGE)) {
          typeString = "(CHANGED KEY) ";
        }  else if (type.equals(DocumentEvent.EventType.INSERT)) {
          typeString = "(PRESSED KEY) ";
        }  else if (type.equals(DocumentEvent.EventType.REMOVE)) {
          typeString = "(DELETED KEY) ";
        }
        System.out.print("Type : " + typeString);
        Document source = documentEvent.getDocument();
        int length = source.getLength();
        System.out.println("Current size: " + length);

      }
    };
area1.getDocument().addDocumentListener(documentListener);
area2.getDocument().addDocumentListener(documentListener);

This is my code for handling when things are pressed in either area1 or area2.

I am trying to make it so that when one area's text is updated, it updates the second area's text with the same text and vice versa. How would I go about doing so? One field is for encrypting something and the other for the decrypted values and vice versa.


回答1:


Just have them share the same Document, that's it.

area1.setDocument(area2.getDocument());


来源:https://stackoverflow.com/questions/26394121/jtextarea-updated-with-documentlistener

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