Example #1
0
  public PlainView(Document doc, JTextComponent component) {
    super(doc);
    this.comp = component;

    // Subscribe to key presses so we know when to mark the document
    // as updated
    comp.addKeyListener(
        new KeyAdapter() {
          public void KeyTyped(KeyEvent e) {
            updateModelFromComponent(comp.getText());
          }
        });

    // Subscribe to Document events so we know when to update
    // the component from the model.
    doc.addDocumentListener(
        new DocumentListener() {
          public void insertUpdate(DocumentEvent e) {
            updateComponentFromModel();
          }

          public void removeUpdate(DocumentEvent e) {
            updateComponentFromModel();
          }

          public void changedUpdate(DocumentEvent e) {
            updateComponentFromModel();
          }
        });
  }
Example #2
0
  /** Reads the text from the model and replaces the text in the component. */
  public void updateComponentFromModel() {

    // We set this flag when a keypress fires a model
    // change - this ensures that if the model was just
    // updated from the component, the resulting Document
    // change doesn't fire a component update (losing
    // the caret position and looking weird to the user).
    // Besides - if this flag is set, the two have just
    // been synced so there's no need to do it again.
    if (componentJustChanged) {
      componentJustChanged = false;
      return;
    }

    try {
      comp.setText(doc.getText(0, doc.getLength()));
    } catch (BadLocationException e) {
      // Shouldn't ever happen
      e.printStackTrace();
    }
  }