Example usage for javax.swing.text Document insertString

List of usage examples for javax.swing.text Document insertString

Introduction

In this page you can find the example usage for javax.swing.text Document insertString.

Prototype

public void insertString(int offset, String str, AttributeSet a) throws BadLocationException;

Source Link

Document

Inserts a string of content.

Usage

From source file:com.hexidec.ekit.EkitCore.java

/**
 * Method for finding (and optionally replacing) a string in the text
 */// ww w  .j  ava2s.c  o m
private int findText(String findTerm, String replaceTerm, boolean bCaseSenstive, int iOffset) {
    JTextComponent jtpFindSource;
    if (sourceWindowActive || jtpSource.hasFocus()) {
        jtpFindSource = (JTextComponent) jtpSource;
    } else {
        jtpFindSource = (JTextComponent) jtpMain;
    }
    int searchPlace = -1;
    try {
        Document baseDocument = jtpFindSource.getDocument();
        searchPlace = (bCaseSenstive
                ? baseDocument.getText(0, baseDocument.getLength()).indexOf(findTerm, iOffset)
                : baseDocument.getText(0, baseDocument.getLength()).toLowerCase()
                        .indexOf(findTerm.toLowerCase(), iOffset));
        if (searchPlace > -1) {
            if (replaceTerm != null) {
                AttributeSet attribs = null;
                if (baseDocument instanceof HTMLDocument) {
                    Element element = ((HTMLDocument) baseDocument).getCharacterElement(searchPlace);
                    attribs = element.getAttributes();
                }
                baseDocument.remove(searchPlace, findTerm.length());
                baseDocument.insertString(searchPlace, replaceTerm, attribs);
                jtpFindSource.setCaretPosition(searchPlace + replaceTerm.length());
                jtpFindSource.requestFocus();
                jtpFindSource.select(searchPlace, searchPlace + replaceTerm.length());
            } else {
                jtpFindSource.setCaretPosition(searchPlace + findTerm.length());
                jtpFindSource.requestFocus();
                jtpFindSource.select(searchPlace, searchPlace + findTerm.length());
            }
        }
    } catch (BadLocationException ble) {
        logException("BadLocationException in actionPerformed method", ble);
        new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("Error"), true,
                Translatrix.getTranslationString("ErrorBadLocationException"), SimpleInfoDialog.ERROR);
    }
    return searchPlace;
}

From source file:org.astrojournal.logging.JTextPaneAppender.java

@Override
public void append(final LogEvent event) {
    final String message = new String(this.getLayout().toByteArray(event));
    try {//from  w w  w.j a v  a 2 s.  com
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    if (jTextPane != null) {
                        try {
                            Document doc = jTextPane.getDocument();
                            if (event.getLevel().equals(Level.DEBUG)) {
                                doc.insertString(doc.getLength(), message, styleSmall);
                            } else if (event.getLevel().equals(Level.INFO)) {
                                if (message.startsWith(
                                        AJMetaInfo.NAME.getInfo() + " " + AJMetaInfo.VERSION.getInfo())) {
                                    doc.insertString(doc.getLength(), message, styleSmallItalic);
                                } else if (message.indexOf("Testing pdflatex") != -1) {
                                    String[] lines = message.split("\n");
                                    doc.insertString(doc.getLength(), lines[0], styleBold);
                                    for (int i = 1; i < lines.length; i++) {
                                        doc.insertString(doc.getLength(), lines[i] + "\n", styleSmallItalic);
                                    }
                                    doc.insertString(doc.getLength(), "\n\n", styleRegular);
                                } else if (StringUtils.countMatches(message, "\n") > 1) {
                                    doc.insertString(doc.getLength(), message, styleSmallItalic);
                                } else if (!message.startsWith("\t")) {
                                    doc.insertString(doc.getLength(), message, styleBold);
                                } else {
                                    doc.insertString(doc.getLength(), message, styleRegular);
                                }
                            } else if (event.getLevel().equals(Level.WARN)) {
                                doc.insertString(doc.getLength(), message, styleBlue);
                            } else {
                                doc.insertString(doc.getLength(), message, styleRed);
                            }
                        } catch (BadLocationException e) {
                            LOGGER.error(e, e);
                        }
                    }
                } catch (final Throwable t) {
                    LOGGER.error("Unable to append log to text pane: " + t.getMessage()
                            + ". Please see help menu for reporting this issue.", t);
                }
            }
        });
    } catch (final IllegalStateException e) {
        LOGGER.error("Unable to append log to text pane: " + e.getMessage()
                + ". Please see help menu for reporting this issue.", e);
    }
}

From source file:org.executequery.gui.editor.autocomplete.QueryEditorAutoCompletePopupProvider.java

public void popupSelectionMade() {

    AutoCompleteListItem selectedListItem = (AutoCompleteListItem) autoCompletePopup.getSelectedItem();

    if (selectedListItem == null || selectedListItem.isNothingProposed()) {

        return;//w w  w. j av  a 2  s.c  o  m
    }

    String selectedValue = selectedListItem.getInsertionValue();

    try {

        JTextComponent textComponent = queryEditorTextComponent();
        Document document = textComponent.getDocument();

        int caretPosition = textComponent.getCaretPosition();
        String wordAtCursor = queryEditor.getWordToCursor();

        if (StringUtils.isNotBlank(wordAtCursor)) {

            int wordAtCursorLength = wordAtCursor.length();
            int insertionIndex = caretPosition - wordAtCursorLength;

            if (selectedListItem.isKeyword() && isAllLowerCase(wordAtCursor)) {

                selectedValue = selectedValue.toLowerCase();
            }

            if (!Character.isLetterOrDigit(wordAtCursor.charAt(0))) {

                // cases where you might have a.column_name or similar

                insertionIndex++;
                wordAtCursorLength--;

            } else if (wordAtCursor.contains(".")) {

                int index = wordAtCursor.indexOf(".");
                insertionIndex += index + 1;
                wordAtCursorLength -= index + 1;
            }

            document.remove(insertionIndex, wordAtCursorLength);
            document.insertString(insertionIndex, selectedValue, null);

        } else {

            document.insertString(caretPosition, selectedValue, null);
        }

    } catch (BadLocationException e) {

        debug("Error on autocomplete insertion", e);

    } finally {

        autoCompletePopup.hidePopup();
    }

}

From source file:org.languagetool.gui.LanguageToolSupport.java

private void applySuggestion(String str, int start, int end) {
    if (end < start) {
        throw new IllegalArgumentException("end before start: " + end + " < " + start);
    }//w  w w  . ja v a 2 s . c o  m
    Document doc = this.textComponent.getDocument();
    if (doc != null) {
        try {
            if (this.undo != null) {
                this.undo.startCompoundEdit();
            }
            if (doc instanceof AbstractDocument) {
                ((AbstractDocument) doc).replace(start, end - start, str, null);
            } else {
                doc.remove(start, end - start);
                doc.insertString(start, str, null);
            }
        } catch (BadLocationException e) {
            throw new IllegalArgumentException(e);
        } finally {
            if (this.undo != null) {
                this.undo.endCompoundEdit();
            }
        }
    }
}

From source file:org.omegat.gui.scripting.ScriptingWindow.java

/**
 * Print log text to the Scripting Window's console area. A trailing line break will be added
 * automatically.//from  ww  w.  j  ava  2 s. c om
 */
private void logResultToWindow(String s) {
    Document doc = m_txtResult.getDocument();
    try {
        doc.insertString(doc.getLength(), s + "\n", null);
    } catch (BadLocationException e1) {
        /* empty */
    }
}

From source file:org.opendatakit.appengine.updater.UpdaterWindow.java

public synchronized void displayOutput(StreamType type, String actionName, String line) {
    Document doc = editorArea.getDocument();

    String str = actionName + ((type == StreamType.ERR) ? "!:  " : " :  ") + line + "\r\n";

    try {/*ww  w  .  j  av  a 2s. c o  m*/
        doc.insertString(doc.getLength(), str, null);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}

From source file:org.opendatakit.briefcase.ui.ScrollingStatusListDialog.java

private void appendToDocument(JTextComponent component, String msg) {
    Document doc = component.getDocument();
    try {/*from w ww .  j  av  a 2  s.  c  o m*/
        doc.insertString(doc.getLength(), "\n" + msg, null);
    } catch (BadLocationException e) {
        LOG.error("Insertion failed: " + e.getMessage());
    }
}

From source file:org.opendatakit.briefcase.ui.ScrollingStatusListDialog.java

@EventSubscriber(eventClass = FormStatusEvent.class)
public void onFormStatusEvent(FormStatusEvent event) {
    // Since there can be multiple FormStatusEvent's published concurrently,
    // we have to check if the event is meant for this dialog instance.
    if (isShowing() && event.getStatus().getFormDefinition().equals(form)) {
        try {/*  w  w w .j a va 2s  . c o m*/
            Document doc = editorArea.getDocument();
            String latestStatus = "\n" + event.getStatusString();
            doc.insertString(doc.getLength(), latestStatus, null);
        } catch (BadLocationException e) {
            LOG.warn("failed to update history", e);
        }
    }
}

From source file:processing.app.EditorTab.java

/**
 * Replace the entire contents of this tab.
 *///from  w ww .j a v  a2 s.  co m
public void setText(String what) {
    // Remove all highlights, since these will all end up at the start of the
    // text otherwise. Preserving them is tricky, so better just remove them.
    textarea.removeAllLineHighlights();
    // Set the caret update policy to NEVER_UPDATE while completely replacing
    // the current text. Normally, the caret tracks inserts and deletions, but
    // replacing the entire text will always make the caret end up at the end,
    // which isn't really useful. With NEVER_UPDATE, the caret will just keep
    // its absolute position (number of characters from the start), which isn't
    // always perfect, but the best we can do without making a diff of the old
    // and new text and some guesswork.
    // Note that we cannot use textarea.setText() here, since that first removes
    // text and then inserts the new text. Even with NEVER_UPDATE, the caret
    // always makes sure to stay valid, so first removing all text makes it
    // reset to 0. Also note that simply saving and restoring the caret position
    // will work, but then the scroll position might change in response to the
    // caret position.
    DefaultCaret caret = (DefaultCaret) textarea.getCaret();
    int policy = caret.getUpdatePolicy();
    caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
    try {
        Document doc = textarea.getDocument();
        int oldLength = doc.getLength();
        // The undo manager already seems to group the insert and remove together
        // automatically, but better be explicit about it.
        textarea.beginAtomicEdit();
        try {
            doc.insertString(oldLength, what, null);
            doc.remove(0, oldLength);
        } catch (BadLocationException e) {
            System.err.println("Unexpected failure replacing text");
        } finally {
            textarea.endAtomicEdit();
        }
    } finally {
        caret.setUpdatePolicy(policy);
    }
}

From source file:tk.tomby.tedit.core.snr.FindReplaceWorker.java

/**
 * DOCUMENT ME!//  w  w  w . j  a v  a 2 s.  c  o m
 */
public void replace() {
    String replace = PreferenceManager.getString("snr.replace", "");

    if ((replace != null) && !replace.equals("")) {
        int start = buffer.getSelectionStart();
        int end = buffer.getSelectionEnd();

        if (start != end) {
            Document doc = buffer.getDocument();

            try {
                doc.remove(start, end - start);
                doc.insertString(start, replace, null);
            } catch (BadLocationException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}