示例#1
0
    public void execute() {
      if (!isEditable() || !isEnabled()) {
        return;
      }

      try {
        int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition();
        lastClickPoint = null;
        Document document = getDocument();
        String selectedText = getSelectedText();
        if (selectedText != null && !CommonUtil.isEmpty(selectedText)) {
          final int selectionEnd = getSelectionEnd();
          document.insertString(selectionEnd, selectedText, null);
          select(selectionEnd, selectionEnd + selectedText.length());
        } else {
          final int docLen = document.getLength();
          int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n'));
          int toIndex = getText(fromIndex + 1, docLen - fromIndex).indexOf('\n');
          toIndex = toIndex < 0 ? docLen : fromIndex + toIndex;
          String textToDuplicate = getText(fromIndex, toIndex - fromIndex + 1);
          if (!textToDuplicate.startsWith("\n")) {
            textToDuplicate = "\n" + textToDuplicate;
          }
          if (textToDuplicate.endsWith("\n")) {
            textToDuplicate = textToDuplicate.substring(0, textToDuplicate.length() - 1);
          }
          document.insertString(Math.min(docLen, toIndex + 1), textToDuplicate, null);
          setCaretPosition(position + textToDuplicate.length());
        }
      } catch (BadLocationException e1) {
        e1.printStackTrace();
      }
    }
  /**
   * Parse the passed text string for style names and add the styled text to the text pane's
   * document.
   *
   * @param text Text to parse
   * @param pane Pane to modify. The pane also provides the style names
   */
  public static final void parse(String text, JTextPane pane) {
    try {
      Matcher match = TEXT_PATTERN.matcher(text);
      Document doc = pane.getDocument();
      int textStart = 0; // Start of current text area
      Style style = null; // Style for next set of text
      while (match.find()) {

        // Save the current text first
        String styledText = text.substring(textStart, match.start());
        textStart = match.end() + 1;
        if (style != null && styledText != null) {
          doc.insertString(doc.getLength(), styledText, style);
        } // endif

        // Get the next style
        style = pane.getStyle(match.group(1));
        if (style == null) throw new IllegalArgumentException("Unknown style: '" + match.group(1));
      } // endwhile

      // Add the last of the text
      doc.insertString(doc.getLength(), text.substring(textStart), null);
    } catch (BadLocationException e) {
      e.printStackTrace();
      throw new IllegalStateException(
          "This should not happen since I always use the document to "
              + "determine the location to write. It might be due to synchronization problems though");
    }
  }
示例#3
0
  private void populateRemark() {
    txtTextField.setText("");
    txtRemark.setText("");
    SimpleAttributeSet BLUE = new SimpleAttributeSet();
    SimpleAttributeSet BLACK = new SimpleAttributeSet();
    StyleConstants.setForeground(BLUE, Color.BLUE);
    StyleConstants.setForeground(BLACK, Color.BLACK);

    Document rmkDoc = txtRemark.getDocument();

    for (int i = remarkslist.size() - 1; i >= 0; i--) {
      RemarkSummary prmk = remarkslist.get(i);
      try {
        if (prmk.getCreatedBy() == null) {
          rmkDoc.insertString(rmkDoc.getLength(), "" + "" + "" + "", BLUE);
        } else {
          rmkDoc.insertString(
              rmkDoc.getLength(), prmk.getDateTime() + " : " + prmk.getCreatedBy() + " : ", BLUE);
        }
        rmkDoc.insertString(rmkDoc.getLength(), prmk.getText() + '\n', BLACK);
      } catch (BadLocationException e) {
        System.out.println("Exception in pnr remark: " + e);
      }
    }
  }
示例#4
0
    public void execute() {
      if (!isEditable() || !isEnabled()) {
        return;
      }
      int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition();
      lastClickPoint = null;
      Document document = getDocument();
      String selectedText = getSelectedText();

      try {
        if (selectedText != null && !CommonUtil.isEmpty(selectedText)) {
          String trimmed = selectedText.trim();
          if (trimmed.startsWith("<!--") && trimmed.endsWith("-->")) {
            StringBuffer buffer = new StringBuffer(selectedText);
            int pos = buffer.indexOf("<!--");
            buffer.delete(pos, pos + 4);
            pos = buffer.lastIndexOf("-->");
            buffer.delete(pos, pos + 3);
            replaceSelection(buffer.toString());
          } else {
            String newSelection = "<!--" + selectedText + "-->";
            replaceSelection(newSelection);
          }
        } else {
          final int docLen = document.getLength();
          int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n'));
          int toIndex = getText(fromIndex + 1, docLen - position).indexOf('\n');
          toIndex = toIndex < 0 ? docLen : fromIndex + toIndex;
          String textToComment = getText(fromIndex, toIndex - fromIndex + 1);

          if (textToComment.startsWith("\n")) {
            textToComment = textToComment.substring(1);
            fromIndex++;
          }
          if (textToComment.endsWith("\n")) {
            textToComment = textToComment.substring(0, textToComment.length() - 1);
            toIndex--;
          }
          String trimmed = textToComment.trim();
          if (trimmed.startsWith("<!--") && trimmed.endsWith("-->")) {
            int pos = textToComment.lastIndexOf("-->");
            document.remove(fromIndex + pos, 3);
            pos = textToComment.indexOf("<!--");
            document.remove(fromIndex + pos, 4);
          } else {
            document.insertString(Math.min(toIndex + 1, docLen), "-->", null);
            document.insertString(fromIndex, "<!--", null);
          }
        }
      } catch (BadLocationException e1) {
        e1.printStackTrace();
      }
    }
  /**
   * Replace the path component under the caret with the file selected from the completion list.
   *
   * @param file the selected file.
   * @param caretPos
   * @param start the start offset of the path component under the caret.
   * @param end the end offset of the path component under the caret.
   * @throws BadLocationException
   */
  private void replacePathComponent(LookupFile file, int caretPos, int start, int end)
      throws BadLocationException {
    final Document doc = myPathTextField.getDocument();

    myPathTextField.setSelectionStart(0);
    myPathTextField.setSelectionEnd(0);

    final String name = file.getName();
    boolean toRemoveExistingName;
    String prefix = "";

    if (caretPos >= start) {
      prefix = doc.getText(start, caretPos - start);
      if (prefix.length() == 0) {
        prefix = doc.getText(start, end - start);
      }
      if (SystemInfo.isFileSystemCaseSensitive) {
        toRemoveExistingName = name.startsWith(prefix) && prefix.length() > 0;
      } else {
        toRemoveExistingName =
            name.toUpperCase().startsWith(prefix.toUpperCase()) && prefix.length() > 0;
      }
    } else {
      toRemoveExistingName = true;
    }

    int newPos;
    if (toRemoveExistingName) {
      doc.remove(start, end - start);
      doc.insertString(start, name, doc.getDefaultRootElement().getAttributes());
      newPos = start + name.length();
    } else {
      doc.insertString(caretPos, name, doc.getDefaultRootElement().getAttributes());
      newPos = caretPos + name.length();
    }

    if (file.isDirectory()) {
      if (!myFinder.getSeparator().equals(doc.getText(newPos, 1))) {
        doc.insertString(
            newPos, myFinder.getSeparator(), doc.getDefaultRootElement().getAttributes());
        newPos++;
      }
    }

    if (newPos < doc.getLength()) {
      if (myFinder.getSeparator().equals(doc.getText(newPos, 1))) {
        newPos++;
      }
    }
    myPathTextField.setCaretPosition(newPos);
  }
示例#6
0
  private static void insertQuestion(final JTextPane textPane, String str) {
    Document doc = textPane.getDocument();
    try {
      doc.insertString(doc.getLength(), str, null);

      final int pos = doc.getLength();
      System.out.println(pos);
      final JTextField field =
          new JTextField(4) {
            @Override
            public Dimension getMaximumSize() {
              return getPreferredSize();
            }
          };
      field.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
      field.addFocusListener(
          new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
              try {
                Rectangle rect = textPane.modelToView(pos);
                rect.grow(0, 4);
                rect.setSize(field.getSize());
                // System.out.println(rect);
                // System.out.println(field.getLocation());
                textPane.scrollRectToVisible(rect);
              } catch (BadLocationException ex) {
                ex.printStackTrace();
              }
            }

            @Override
            public void focusLost(FocusEvent e) {
              /* not needed */
            }
          });
      Dimension d = field.getPreferredSize();
      int baseline = field.getBaseline(d.width, d.height);
      field.setAlignmentY(baseline / (float) d.height);

      SimpleAttributeSet a = new SimpleAttributeSet();
      StyleConstants.setLineSpacing(a, 1.5f);
      textPane.setParagraphAttributes(a, true);

      textPane.insertComponent(field);
      doc.insertString(doc.getLength(), "\n", null);
    } catch (BadLocationException e) {
      e.printStackTrace();
    }
  }
 /** Replaces the current word token */
 public void replaceWord(String newWord) {
   if (currentWordPos != -1) {
     try {
       /* ORIGINAL
         document.remove(currentWordPos, currentWordEnd - currentWordPos);
         document.insertString(currentWordPos, newWord, null);
       */
       // Howard's Version for Ekit
       Element element =
           ((javax.swing.text.html.HTMLDocument) document).getCharacterElement(currentWordPos);
       AttributeSet attribs = element.getAttributes();
       document.remove(currentWordPos, currentWordEnd - currentWordPos);
       document.insertString(currentWordPos, newWord, attribs);
       // End Howard's Version
       // Need to reset the segment
       document.getText(0, document.getLength(), text);
     } catch (BadLocationException ex) {
       throw new RuntimeException(ex.getMessage());
     }
     // Position after the newly replaced word(s)
     // Position after the newly replaced word(s)
     first = true;
     currentWordPos = getNextWordStart(text, currentWordPos + newWord.length());
     if (currentWordPos != -1) {
       currentWordEnd = getNextWordEnd(text, currentWordPos);
       nextWordPos = getNextWordStart(text, currentWordEnd);
       sentanceIterator.setText(text);
       sentanceIterator.following(currentWordPos);
     } else moreTokens = false;
   }
 }
  public void addToUses(String strType, boolean bTemplate, boolean bProgram) {
    if (isTypeUsed(strType)) {
      return;
    }

    Document doc = _gsEditor.getEditor().getDocument();
    int iPos = findUsesInsertionPosition(bProgram);
    int iIndex = doc.getDefaultRootElement().getElementIndex(iPos);
    int iInsertionPt;
    String strUsesStmt = Keyword.KW_uses + " " + strType;
    if (bTemplate) {
      strUsesStmt = "<% " + strUsesStmt + " %>";
    }
    strUsesStmt += "\n";

    if (iPos == 0) {
      iInsertionPt = iPos;
      if (!bTemplate) {
        strUsesStmt = strUsesStmt + "\n";
      }
    } else {
      iInsertionPt = doc.getDefaultRootElement().getElement(iIndex).getEndOffset();
    }

    try {
      doc.insertString(iInsertionPt, strUsesStmt, null);
    } catch (BadLocationException e) {
      throw new RuntimeException(e);
    }
  }
  public void print(final String line) {
    if (!SwingUtilities.isEventDispatchThread()) {
      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              ConsoleTab.this.print(line);
            }
          });
      return;
    }

    Document document = this.console.getDocument();
    JScrollBar scrollBar = getVerticalScrollBar();
    boolean shouldScroll = false;

    if (getViewport().getView() == this.console) {
      shouldScroll =
          scrollBar.getValue() + scrollBar.getSize().getHeight() + MONOSPACED.getSize() * 4
              > scrollBar.getMaximum();
    }
    try {
      document.insertString(document.getLength(), line, null);
    } catch (BadLocationException localBadLocationException) {
    }
    if (shouldScroll) scrollBar.setValue(2147483647);
  }
  void appendOutput(final String line) {
    if (!EventQueue.isDispatchThread()) {
      EventQueue.invokeLater(
          new Runnable() {
            public void run() {
              appendOutput(line);
            }
          });

      return;
    }
    if (!isShowing()) { // ignore request, dialog is closed
      return;
    }

    // Can now accept user input
    outputArea.setEditable(true);
    Document doc = outputArea.getDocument();

    if (doc != null) {
      try {
        doc.insertString(doc.getLength(), line + "\n", null); // NOI18N
      } catch (BadLocationException e) {
      }
    }
  }
示例#11
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);
    }
  }
  /** @param singleFormatter */
  protected void fillWithObjFormatter(final DataObjDataFieldFormatIFace singleFormatter) {
    ignoreFmtChange = true;
    try {
      formatEditor.setText("");

      if (singleFormatter == null) {
        return;
      }

      Document doc = formatEditor.getDocument();
      DataObjDataField[] fields = singleFormatter.getFields();
      if (fields == null) {
        return;
      }

      for (DataObjDataField field : fields) {
        try {
          doc.insertString(doc.getLength(), field.getSep(), null);

          // System.err.println("["+field.getName()+"]["+field.getSep()+"]["+field.getFormat()+"]["+field.toString()+"]");
          insertFieldIntoTextEditor(new DataObjDataFieldWrapper(field));
        } catch (BadLocationException ble) {
        }
      }
    } finally {
      ignoreFmtChange = false;
    }
  }
 public void setNote(String s) {
   try {
     myNote.remove(0, myNote.getLength());
     myNote.insertString(0, s, null);
   } catch (Throwable t) {
     t.printStackTrace();
   }
 }
 private void addText(String str, String styleName, JTextPane pane) {
   Document doc = pane.getDocument();
   int len = doc.getLength();
   try {
     doc.insertString(len, str, pane.getStyle(styleName));
   } catch (javax.swing.text.BadLocationException e) {
   }
 }
示例#15
0
 protected void append(JTextPane field, final String change) {
   Document document = field.getDocument();
   try {
     document.insertString(document.getLength(), change, null);
   } catch (BadLocationException e) {
     throw new NotImplementedYet(e); // Fix Handle this exception.
   }
 }
  public void testInsertStringIntStringAttributeSet() throws Exception {
    String[] items = new String[] {"exact", "exacter", "exactest"};

    JTextComponent textComponent = new JTextField("012345");
    TextComponentAdaptor adaptor = new TextComponentAdaptor(textComponent, Arrays.asList(items));
    Document document = new AutoCompleteDocument(adaptor, false);
    document.insertString(0, "test", null);
  }
示例#17
0
 private void logResult(JEditorPane e, String s) {
   Document doc = e.getDocument();
   try {
     doc.insertString(doc.getLength(), s, null);
   } catch (BadLocationException e1) {
     /* empty */
   }
 }
示例#18
0
 private void insertString(int pos, String str) {
   Document doc = getDocument();
   try {
     doc.insertString(pos, str, null);
   } catch (Exception e) {
     Debug.error(me + "insertString: Problem while trying to insert at pos\n%s", e.getMessage());
   }
 }
示例#19
0
 private void checkCompletion(java.awt.event.KeyEvent ke) throws BadLocationException {
   Document doc = getDocument();
   Element root = doc.getDefaultRootElement();
   int pos = getCaretPosition();
   int lineIdx = root.getElementIndex(pos);
   Element line = root.getElement(lineIdx);
   int start = line.getStartOffset(), len = line.getEndOffset() - start;
   String strLine = doc.getText(start, len - 1);
   Debug.log(9, "[" + strLine + "]");
   if (strLine.endsWith("find") && ke.getKeyChar() == '(') {
     ke.consume();
     doc.insertString(pos, "(", null);
     ButtonCapture btnCapture = new ButtonCapture(this, line);
     insertComponent(btnCapture);
     doc.insertString(pos + 2, ")", null);
   }
 }
示例#20
0
 @Override
 public void setValue(java.lang.String value) {
   try {
     document.remove(0, document.getLength());
     document.insertString(0, value, null);
   } catch (final BadLocationException e) {
     throw new RuntimeException(e);
   }
 }
  public void displayReducedClassesNames(List<String> classNamesToShow, String inputText) {
    displayDataState = DisplayDataState.CLASSES_LIST;

    clearText();

    int matchIndex;

    String beforeMatch = "";
    String match;
    String afterMatch = "";

    StyleConstants.setFontSize(style, 18);
    StyleConstants.setForeground(style, ColorScheme.FOREGROUND_CYAN);

    Document doc = jTextPane.getDocument();

    for (String className : classNamesToShow) {
      matchIndex = className.indexOf(inputText);

      if (matchIndex > -1) {
        beforeMatch = className.substring(0, matchIndex);
        match = className.substring(matchIndex, matchIndex + inputText.length());
        afterMatch = className.substring(matchIndex + inputText.length(), className.length());
      } else {
        // we are here by camel match
        // i.e. 2-3 letters that fits
        // to class name
        match = className;
      }

      try {
        doc.insertString(doc.getLength(), beforeMatch, style);
        StyleConstants.setBackground(style, ColorScheme.SELECTION_BG);
        doc.insertString(doc.getLength(), match, style);
        StyleConstants.setBackground(style, ColorScheme.BACKGROUND);
        doc.insertString(doc.getLength(), afterMatch + "\n", style);
      } catch (BadLocationException e) {
        e.printStackTrace();
      }
    }

    jTextPane.setDocument(doc);
  }
示例#22
0
 private static TokenSequence<SQLTokenId> getTokenSequence(String sql)
     throws BadLocationException {
   Document doc = new ModificationTextDocument();
   doc.insertString(0, sql, null);
   doc.putProperty(Language.class, SQLTokenId.language());
   TokenHierarchy<?> hi = TokenHierarchy.get(doc);
   TokenSequence<SQLTokenId> seq = hi.tokenSequence(SQLTokenId.language());
   seq.moveStart();
   return seq;
 }
  public void addText(String text) {
    try {
      if (sdoc != null) sdoc.insertString(offset, text, currentStyle);
      else doc.insertString(offset, text, null);

      offset += text.length();
    } catch (BadLocationException e) {
      // todo: throw it to RTFEditorKit?
    }
  }
 /*
  * append(String s, Color color){...}
  * This method is the same as append(String s) except
  * that this method also changes the color of the
  * indicated text instead of defaulting to white.
  */
 public static void append(String s, Color color) {
   style = tPane.addStyle("Styles", null);
   StyleConstants.setForeground(style, color);
   try {
     doc.insertString(doc.getLength(), s, style);
   } catch (BadLocationException ex) {
     System.out.println("BadLocationException ex caught.");
   }
   tPane.setCaretPosition(tPane.getDocument().getLength());
 }
 private void insertDocument(String text, Color textColor) {
   SimpleAttributeSet set = new SimpleAttributeSet();
   StyleConstants.setForeground(set, textColor);
   StyleConstants.setFontSize(set, 12);
   Document doc = progressArea.getStyledDocument();
   try {
     doc.insertString(doc.getLength(), text, set);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
示例#26
0
 private void appendText(String s) {
   try {
     // jtextArea.setText( jtextArea.getText() + s );	// this line is shorter, but much less
     // efficient, than the lines below...
     Document document = jtextArea.getDocument();
     int offset = document.getLength();
     document.insertString(offset, s, null);
   } catch (Throwable t) {
     throw ThrowableUtil.toRuntimeException(t);
   }
 }
  /**
   * Test method for {@link ext.AutoCompleteDocument#remove(int, int)}.
   *
   * @throws Exception
   */
  public void testRemove() throws Exception {
    String[] items = new String[] {"exact", "exacter", "exactest"};

    JTextComponent textComponent = new JTextField();
    TextComponentAdaptor adaptor = new TextComponentAdaptor(textComponent, Arrays.asList(items));
    Document document = new AutoCompleteDocument(adaptor, true);
    document.insertString(0, "test", null);

    // TODO: this does not work for some reason....
    // document.remove(0, 2);
  }
示例#28
0
 // TODO not used
 public void appendString(String str) {
   Document doc = getDocument();
   try {
     int start = doc.getLength();
     doc.insertString(doc.getLength(), str, null);
     int end = doc.getLength();
     // end = parseLine(start, end, patHistoryBtnStr);
   } catch (Exception e) {
     Debug.error(me + "appendString: Problem while trying to append\n%s", e.getMessage());
   }
 }
 private void addString(final String str) {
   final Document doc = target.getDocument();
   if (doc != null) {
     try {
       // Application.instance.getMainFrame().updateContentPanel(true);
       doc.insertString(doc.getLength(), str, null);
       target.setCaretPosition(target.getText().length());
     } catch (final BadLocationException e) {
     }
   }
 }
示例#30
0
  private synchronized void writeMessageText(String message) {
    SimpleAttributeSet attrTS = new SimpleAttributeSet();
    attrTS.addAttribute(ColorConstants.Foreground, Color.DARK_GRAY);
    attrTS.addAttribute(StyleConstants.Bold, true);
    logMsg.setValue("source", "ccu");
    logMsg.setValue("destination", "ccu");

    Document doc = msgTextArea.getDocument();
    try {
      SimpleAttributeSet attr = new SimpleAttributeSet();
      attr.addAttribute(ColorConstants.Foreground, Color.blue);
      doc.insertString(doc.getLength(), "[" + getTimeStamp() + "]: ", attrTS);

      attr = new SimpleAttributeSet();
      attr.addAttribute(ColorConstants.Foreground, Color.black);
      doc.insertString(doc.getLength(), message + "\n", attr);

      msgTextArea.setCaretPosition(doc.getLength());
    } catch (Exception e) {
    }
  }