Exemplo n.º 1
0
  /**
   * Накат истории вперед
   *
   * @param target Запись истории
   * @param textPane Текст для которого применяется историческое изменение
   */
  public static void applyForward(UndoTextAction target, JTextComponent textPane) {
    if (target == null) throw new IllegalArgumentException("target==null");
    if (textPane == null) throw new IllegalArgumentException("textPane==null");

    try {
      javax.swing.text.Document doc = textPane.getDocument();

      int offset = target.getOffset();
      String changes = target.getChangedText();

      if (UndoTextAction.Action.Added.equals(target.getAction())) {
        doc.insertString(offset, changes, null);

        int L = doc.getLength();
        int P = offset + changes.length();
        if (P > L) P = L;
        textPane.setCaretPosition(P);
      } else if (UndoTextAction.Action.Deleted.equals(target.getAction())) {
        doc.remove(offset, changes.length());

        textPane.setCaretPosition(offset);
      }
    } catch (BadLocationException ex) {
      Logger.getLogger(UndoTextAction.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Exemplo n.º 2
0
  /**
   * Откат истории назад
   *
   * @param target Запись истории
   * @param snapshot Текст для которого применяется историческое изменение
   * @return Текст модифицированный записью
   */
  public static String applyBack(UndoTextAction target, String snapshot) {
    if (target == null) throw new IllegalArgumentException("target==null");
    if (snapshot == null) throw new IllegalArgumentException("snapshot==null");

    String text = snapshot;
    int offset = target.getOffset();
    int textLen = text.length();
    String changes = target.getChangedText();
    String before = null;
    String after = null;
    String res = null;

    if (UndoTextAction.Action.Added.equals(target.getAction())) {
      StringBuilder sb = new StringBuilder();

      before = (offset > 0 && offset <= textLen) ? text.substring(0, offset) : "";

      int cutOffset = offset + changes.length();
      after = (cutOffset > 0 && cutOffset <= textLen) ? text.substring(cutOffset) : "";

      sb.append(before);
      sb.append(after);

      res = sb.toString();
    } else if (UndoTextAction.Action.Deleted.equals(target.getAction())) {
      StringBuilder sb = new StringBuilder();

      before = (offset > 0 && offset <= textLen) ? text.substring(0, offset) : "";
      after = (offset > 0 && offset <= textLen) ? text.substring(offset) : "";

      sb.append(before);
      sb.append(changes);
      sb.append(after);

      res = sb.toString();
    }

    return res;
  }