Example usage for javax.swing.text Document getLength

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

Introduction

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

Prototype

public int getLength();

Source Link

Document

Returns number of characters of content currently in the document.

Usage

From source file:multiplayer.pong.client.LobbyFrame.java

private void appendMessage(String message, SimpleAttributeSet set) {
    // If no set of styles was passed, use the default
    if (set == null)
        set = new SimpleAttributeSet();
    Document doc = ta.getStyledDocument();
    try {//  w  w w. j  a  v  a 2  s  .c  om
        doc.insertString(doc.getLength(), message, set);
    } catch (BadLocationException e) {
    }
}

From source file:de.huxhorn.lilith.swing.preferences.PreferencesDialog.java

public void editDetailsFormatter() {
    Console console = new Console();
    File messageViewRoot = applicationPreferences.getDetailsViewRoot();
    File messageViewGroovyFile = new File(messageViewRoot, ApplicationPreferences.DETAILS_VIEW_GROOVY_FILENAME);

    EventWrapper<LoggingEvent> eventWrapper = new EventWrapper<>(
            new SourceIdentifier("identifier", "secondaryIdentifier"), 17, new LoggingEvent());
    console.setVariable("eventWrapper", eventWrapper);

    console.setCurrentFileChooserDir(messageViewRoot);
    String text = "";
    if (!messageViewGroovyFile.isFile()) {
        applicationPreferences.initDetailsViewRoot(true);
    }//from   ww w  .  j a  v a 2s.com
    if (messageViewGroovyFile.isFile()) {
        InputStream is;
        try {
            is = new FileInputStream(messageViewGroovyFile);
            List lines = IOUtils.readLines(is, StandardCharsets.UTF_8);
            boolean isFirst = true;
            StringBuilder textBuffer = new StringBuilder();
            for (Object o : lines) {
                String s = (String) o;
                if (isFirst) {
                    isFirst = false;
                } else {
                    textBuffer.append("\n");
                }
                textBuffer.append(s);
            }
            text = textBuffer.toString();
        } catch (IOException e) {
            if (logger.isInfoEnabled()) {
                logger.info("Exception while reading '" + messageViewGroovyFile.getAbsolutePath() + "'.", e);
            }
        }
    } else {
        if (logger.isWarnEnabled())
            logger.warn("Failed to initialize detailsView file '{}'!", messageViewGroovyFile.getAbsolutePath());
    }
    console.run(); // initializes everything

    console.setScriptFile(messageViewGroovyFile);
    JTextPane inputArea = console.getInputArea();
    //inputArea.setText(text);
    Document doc = inputArea.getDocument();
    try {
        doc.remove(0, doc.getLength());
        doc.insertString(0, text, null);
    } catch (BadLocationException e) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while setting source!", e);
    }
    console.setDirty(false);
    inputArea.setCaretPosition(0);
    inputArea.requestFocusInWindow();
}

From source file:edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatSinglePanel.java

/**
 * @param singleFormatter/*from   w w w. j  a  va  2 s.c om*/
 */
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;
    }
}

From source file:com.hexidec.ekit.component.ExtendedHTMLEditorKit.java

@Override
public void read(Reader in, Document doc, int pos) throws IOException, BadLocationException {
    String html = IOUtils.toString(in);

    //      log.debug("read [" + html + "]");

    html = HTMLUtilities.preparaPaste(html);

    ExtendedHTMLDocument htmlDoc = (ExtendedHTMLDocument) doc;

    html = htmlDoc.filterRead(html, pos);

    htmlDoc.setEdicaoControlada(false);//from  w w w .  java2  s.c om

    if (StringUtils.isEmpty(html)) {
        return;
    }

    if (htmlDoc.isInlineEdit() || HTMLUtilities.isInline(html)) {
        html = "<span>" + html + "</span>";
        insertHTML((HTMLDocument) doc, pos, html, 0, 0, Tag.SPAN);
    } else if (DocumentUtil.getElementByTag((HTMLDocument) doc, pos, Tag.TD) != null) {
        // Retira pargrafos ao colar dentro de clula para evitar quebra da tabela.
        html = "<span>" + HTMLUtilities.removeTag(html, Tag.P) + "<span>";
        insertHTML((HTMLDocument) doc, pos, html, 0, 0, Tag.SPAN);
    } else {

        if (pos == doc.getLength() && HTMLUtilities.terminaComTabela(html)) {
            // Evita que o texto termine com tabela,
            // caso em que no se consegue apagar a tabela devido a bug do swing.
            html += "<p></p>";
        }

        super.read(new StringReader(html), doc, pos);
    }

    // Verifica se leu alguma clula de tabela.
    if (HTMLUtilities.contemTag(html, Tag.TD)) {
        DocumentUtil.corrigeTabelas(htmlDoc, this);
    }

}

From source file:ch.zhaw.iamp.rct.ui.GrammarWindow.java

private void removeTabIfPossilbe(KeyEvent event, JTextComponent component) {
    try {//from   w ww .  jav  a 2  s.  c o  m
        Document doc = component.getDocument();
        int caretPostion = component.getCaretPosition();
        int lineStartIndex = doc.getText(0, caretPostion).lastIndexOf('\n') + 1;
        lineStartIndex = lineStartIndex < 0 ? 0 : lineStartIndex;
        lineStartIndex = lineStartIndex >= doc.getLength() ? doc.getLength() - 1 : lineStartIndex;
        int scanEndIndex = lineStartIndex + 4 <= doc.getLength() ? lineStartIndex + 4 : doc.getLength();

        for (int i = 0; i < 4 && i + lineStartIndex < scanEndIndex; i++) {
            if (doc.getText(lineStartIndex, 1).matches(" ")) {
                doc.remove(lineStartIndex, 1);
            } else if (doc.getText(lineStartIndex, 1).matches("\t")) {
                doc.remove(lineStartIndex, 1);
                break;
            } else {
                break;
            }
        }

        event.consume();
    } catch (BadLocationException ex) {
        System.out.println("Could not insert a tab: " + ex.getMessage());
    }
}

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatWritePanel.java

/**
 * Returns the write area text as a plain text without any formatting.
 *
 * @return the write area text as a plain text without any formatting.
 *///from w ww .j ava2  s.co m
public String getText() {
    try {
        Document doc = editorPane.getDocument();

        return doc.getText(0, doc.getLength());
    } catch (BadLocationException e) {
        logger.error("Could not obtain write area text.", e);
    }

    return null;
}

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatWritePanel.java

/**
 * When CTRL+Z is pressed invokes the <code>ChatWritePanel.undo()</code>
 * method, when CTRL+R is pressed invokes the
 * <code>ChatWritePanel.redo()</code> method.
 *
 * @param e the <tt>KeyEvent</tt> that notified us
 *//*from  w ww.ja va  2 s  .c  o m*/
public void keyPressed(KeyEvent e) {
    if ((e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK && (e.getKeyCode() == KeyEvent.VK_Z)
    // And not ALT(right ALT gives CTRL + ALT).
            && (e.getModifiers() & KeyEvent.ALT_MASK) != KeyEvent.ALT_MASK) {
        if (undo.canUndo())
            undo();
    } else if ((e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK
            && (e.getKeyCode() == KeyEvent.VK_R)
            // And not ALT(right ALT gives CTRL + ALT).
            && (e.getModifiers() & KeyEvent.ALT_MASK) != KeyEvent.ALT_MASK) {
        if (undo.canRedo())
            redo();
    } else if (e.getKeyCode() == KeyEvent.VK_TAB) {
        if (!(chatPanel.getChatSession() instanceof ConferenceChatSession))
            return;

        e.consume();
        int index = ((JEditorPane) e.getSource()).getCaretPosition();

        StringBuffer message = new StringBuffer(chatPanel.getMessage());

        int position = index - 1;

        while (position > 0 && (message.charAt(position) != ' ')) {
            position--;
        }

        if (position != 0)
            position++;

        String sequence = message.substring(position, index);

        if (sequence.length() <= 0) {
            // Do not look for matching contacts if the matching pattern is
            // 0 chars long, since all contacts will match.
            return;
        }

        Iterator<ChatContact<?>> iter = chatPanel.getChatSession().getParticipants();
        ArrayList<String> contacts = new ArrayList<String>();
        while (iter.hasNext()) {
            ChatContact<?> c = iter.next();
            if (c.getName().length() >= (index - position)
                    && c.getName().substring(0, index - position).equals(sequence)) {
                message.replace(position, index, c.getName().substring(0, index - position));
                contacts.add(c.getName());
            }
        }

        if (contacts.size() > 1) {
            char key = contacts.get(0).charAt(index - position - 1);
            int pos = index - position - 1;
            boolean flag = true;

            while (flag) {
                try {
                    for (String name : contacts) {
                        if (key != name.charAt(pos)) {
                            flag = false;
                        }
                    }

                    if (flag) {
                        pos++;
                        key = contacts.get(0).charAt(pos);
                    }
                } catch (IndexOutOfBoundsException exp) {
                    flag = false;
                }
            }

            message.replace(position, index, contacts.get(0).substring(0, pos));

            Iterator<String> contactIter = contacts.iterator();
            String contactList = "<DIV align='left'><h5>";
            while (contactIter.hasNext()) {
                contactList += contactIter.next() + " ";
            }
            contactList += "</h5></DIV>";

            chatPanel.getChatConversationPanel().appendMessageToEnd(contactList,
                    ChatHtmlUtils.HTML_CONTENT_TYPE);
        } else if (contacts.size() == 1) {
            String limiter = (position == 0) ? ": " : "";
            message.replace(position, index, contacts.get(0) + limiter);
        }

        try {
            ((JEditorPane) e.getSource()).getDocument().remove(0,
                    ((JEditorPane) e.getSource()).getDocument().getLength());
            ((JEditorPane) e.getSource()).getDocument().insertString(0, message.toString(), null);
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    } else if (e.getKeyCode() == KeyEvent.VK_UP) {
        // Only enters editing mode if the write panel is empty in
        // order not to lose the current message contents, if any.
        if (this.chatPanel.getLastSentMessageUID() != null && this.chatPanel.isWriteAreaEmpty()) {
            this.chatPanel.startLastMessageCorrection();
            e.consume();
        }
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
        if (chatPanel.isMessageCorrectionActive()) {
            Document doc = editorPane.getDocument();
            if (editorPane.getCaretPosition() == doc.getLength()) {
                chatPanel.stopMessageCorrection();
            }
        }
    }
}

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatPanel.java

/**
 * Checks if the editor contains text./* ww w  . ja  v  a 2  s  .  co  m*/
 *
 * @return TRUE if editor contains text, FALSE otherwise.
 */
public boolean isWriteAreaEmpty() {
    JEditorPane editorPane = getChatWritePanel().getEditorPane();

    Document doc = editorPane.getDocument();

    try {
        String text = doc.getText(0, doc.getLength());

        if (text == null || text.equals(""))
            return true;
    } catch (BadLocationException e) {
        logger.error("Failed to obtain document text.", e);
    }

    return false;
}

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatPanel.java

/**
 * Returns the message written by user in the chat write area.
 *
 * @return the message written by user in the chat write area
 *///  w w  w.j a v  a  2  s . co m
public String getMessage() {
    Document writeEditorDoc = writeMessagePanel.getEditorPane().getDocument();

    try {
        return writeEditorDoc.getText(0, writeEditorDoc.getLength());
    } catch (BadLocationException e) {
        return writeMessagePanel.getEditorPane().getText();
    }
}

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

/**
 * Method for finding (and optionally replacing) a string in the text
 *//*from   ww  w  .jav a2  s  . c  om*/
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;
}