Example usage for javax.swing.text Document getText

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

Introduction

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

Prototype

public String getText(int offset, int length) throws BadLocationException;

Source Link

Document

Fetches the text contained within the given portion of the document.

Usage

From source file:Main.java

/**
 * Prints a <code>Document</code> using a monospaced font, word wrapping on
 * the characters ' ', '\t', '\n', ',', '.', and ';'.  This method is
 * expected to be called from Printable 'print(Graphics g)' functions.
 *
 * @param g The graphics context to write to.
 * @param doc The <code>javax.swing.text.Document</code> to print.
 * @param fontSize the point size to use for the monospaced font.
 * @param pageIndex The page number to print.
 * @param pageFormat The format to print the page with.
 * @param tabSize The number of spaces to expand tabs to.
 *
 * @see #printDocumentMonospaced//from   ww w . jav a  2 s. com
 */
public static int printDocumentMonospacedWordWrap(Graphics g, Document doc, int fontSize, int pageIndex,
        PageFormat pageFormat, int tabSize) {

    g.setColor(Color.BLACK);
    g.setFont(new Font("Monospaced", Font.PLAIN, fontSize));

    // Initialize our static variables (these are used by our tab expander below).
    tabSizeInSpaces = tabSize;
    fm = g.getFontMetrics();

    // Create our tab expander.
    //RPrintTabExpander tabExpander = new RPrintTabExpander();

    // Get width and height of characters in this monospaced font.
    int fontWidth = fm.charWidth('w'); // Any character will do here, since font is monospaced.
    int fontHeight = fm.getHeight();

    int MAX_CHARS_PER_LINE = (int) pageFormat.getImageableWidth() / fontWidth;
    int MAX_LINES_PER_PAGE = (int) pageFormat.getImageableHeight() / fontHeight;

    final int STARTING_LINE_NUMBER = MAX_LINES_PER_PAGE * pageIndex;

    // The (x,y) coordinate to print at (in pixels, not characters).
    // Since y is the baseline of where we'll start printing (not the top-left
    // corner), we offset it by the font's ascent ( + 1 just for good measure).
    xOffset = (int) pageFormat.getImageableX();
    int y = (int) pageFormat.getImageableY() + fm.getAscent() + 1;

    // A counter to keep track of the number of lines that WOULD HAVE been
    // printed if we were printing all lines.
    int numPrintedLines = 0;

    // Keep going while there are more lines in the document.
    currentDocLineNumber = 0; // The line number of the document we're currently on.
    rootElement = doc.getDefaultRootElement(); // To shorten accesses in our loop.
    numDocLines = rootElement.getElementCount(); // The number of lines in our document.
    while (currentDocLineNumber < numDocLines) {

        // Get the line we are going to print.
        String curLineString;
        Element currentLine = rootElement.getElement(currentDocLineNumber);
        int startOffs = currentLine.getStartOffset();
        try {
            curLineString = doc.getText(startOffs, currentLine.getEndOffset() - startOffs);
        } catch (BadLocationException ble) { // Never happens
            ble.printStackTrace();
            return Printable.NO_SUCH_PAGE;
        }

        // Remove newlines, because they end up as boxes if you don't; this is a monospaced font.
        curLineString = curLineString.replaceAll("\n", "");

        // Replace tabs with how many spaces they should be.
        if (tabSizeInSpaces == 0) {
            curLineString = curLineString.replaceAll("\t", "");
        } else {
            int tabIndex = curLineString.indexOf('\t');
            while (tabIndex > -1) {
                int spacesNeeded = tabSizeInSpaces - (tabIndex % tabSizeInSpaces);
                String replacementString = "";
                for (int i = 0; i < spacesNeeded; i++)
                    replacementString += ' ';
                // Note that "\t" is actually a regex for this method.
                curLineString = curLineString.replaceFirst("\t", replacementString);
                tabIndex = curLineString.indexOf('\t');
            }
        }

        // If this document line is too long to fit on one printed line on the page,
        // break it up into multpile lines.
        while (curLineString.length() > MAX_CHARS_PER_LINE) {

            int breakPoint = getLineBreakPoint(curLineString, MAX_CHARS_PER_LINE) + 1;

            numPrintedLines++;
            if (numPrintedLines > STARTING_LINE_NUMBER) {
                g.drawString(curLineString.substring(0, breakPoint), xOffset, y);
                y += fontHeight;
                if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE)
                    return Printable.PAGE_EXISTS;
            }

            curLineString = curLineString.substring(breakPoint, curLineString.length());

        }

        currentDocLineNumber += 1; // We have printed one more line from the document.

        numPrintedLines++;
        if (numPrintedLines > STARTING_LINE_NUMBER) {
            g.drawString(curLineString, xOffset, y);
            y += fontHeight;
            if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE)
                return Printable.PAGE_EXISTS;
        }

    }

    // Now, the whole document has been "printed."  Decide if this page had any text on it or not.
    if (numPrintedLines > STARTING_LINE_NUMBER)
        return Printable.PAGE_EXISTS;
    return Printable.NO_SUCH_PAGE;

}

From source file:EditorPaneExample16.java

public Heading getNextHeading(Document doc, ElementIterator iter) {
    Element elem;/*from  w w w.j a va2  s. c  om*/

    while ((elem = iter.next()) != null) {
        AttributeSet attrs = elem.getAttributes();
        Object type = attrs.getAttribute(StyleConstants.NameAttribute);
        int level = getHeadingLevel(type);
        if (level > 0) {
            // It is a heading - get the text
            String headingText = "";
            int count = elem.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = elem.getElement(i);
                AttributeSet cattrs = child.getAttributes();
                if (cattrs.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    try {
                        int offset = child.getStartOffset();
                        headingText += doc.getText(offset, child.getEndOffset() - offset);
                    } catch (BadLocationException e) {
                    }
                }
            }
            headingText = headingText.trim();
            return new Heading(headingText, level, elem.getStartOffset());
        }
    }
    return null;
}

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   www  . j  av a2 s.c o 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.ChatPanel.java

/**
 * Checks if the editor contains text.//w w w.ja  v  a2  s  .  c  o 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
 *//*from  w  ww  . ja  v a  2  s  .  c o  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
 *///  w ww  .  jav a  2 s  . 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:net.sf.jasperreports.engine.util.JEditorPaneHtmlMarkupProcessor.java

@Override
public String convert(String srcText) {
    JEditorPane editorPane = new JEditorPane("text/html", srcText);
    editorPane.setEditable(false);//from   w ww .  j a  va 2s .  c o m

    List<Element> elements = new ArrayList<Element>();

    Document document = editorPane.getDocument();

    Element root = document.getDefaultRootElement();
    if (root != null) {
        addElements(elements, root);
    }

    int startOffset = 0;
    int endOffset = 0;
    int crtOffset = 0;
    String chunk = null;
    JRPrintHyperlink hyperlink = null;
    Element element = null;
    Element parent = null;
    boolean bodyOccurred = false;
    int[] orderedListIndex = new int[elements.size()];
    String whitespace = "    ";
    String[] whitespaces = new String[elements.size()];
    for (int i = 0; i < elements.size(); i++) {
        whitespaces[i] = "";
    }

    StringBuilder text = new StringBuilder();
    List<JRStyledText.Run> styleRuns = new ArrayList<>();

    for (int i = 0; i < elements.size(); i++) {
        if (bodyOccurred && chunk != null) {
            text.append(chunk);
            Map<Attribute, Object> styleAttributes = getAttributes(element.getAttributes());
            if (hyperlink != null) {
                styleAttributes.put(JRTextAttribute.HYPERLINK, hyperlink);
                hyperlink = null;
            }
            if (!styleAttributes.isEmpty()) {
                styleRuns.add(
                        new JRStyledText.Run(styleAttributes, startOffset + crtOffset, endOffset + crtOffset));
            }
        }

        chunk = null;
        element = elements.get(i);
        parent = element.getParentElement();
        startOffset = element.getStartOffset();
        endOffset = element.getEndOffset();
        AttributeSet attrs = element.getAttributes();

        Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
        Object object = (elementName != null) ? null : attrs.getAttribute(StyleConstants.NameAttribute);
        if (object instanceof HTML.Tag) {

            HTML.Tag htmlTag = (HTML.Tag) object;
            if (htmlTag == Tag.BODY) {
                bodyOccurred = true;
                crtOffset = -startOffset;
            } else if (htmlTag == Tag.BR) {
                chunk = "\n";
            } else if (htmlTag == Tag.OL) {
                orderedListIndex[i] = 0;
                String parentName = parent.getName().toLowerCase();
                whitespaces[i] = whitespaces[elements.indexOf(parent)] + whitespace;
                if (parentName.equals("li")) {
                    chunk = "";
                } else {
                    chunk = "\n";
                    ++crtOffset;
                }
            } else if (htmlTag == Tag.UL) {
                whitespaces[i] = whitespaces[elements.indexOf(parent)] + whitespace;

                String parentName = parent.getName().toLowerCase();
                if (parentName.equals("li")) {
                    chunk = "";
                } else {
                    chunk = "\n";
                    ++crtOffset;
                }

            } else if (htmlTag == Tag.LI) {

                whitespaces[i] = whitespaces[elements.indexOf(parent)];
                if (element.getElement(0) != null && (element.getElement(0).getName().toLowerCase().equals("ol")
                        || element.getElement(0).getName().toLowerCase().equals("ul"))) {
                    chunk = "";
                } else if (parent.getName().equals("ol")) {
                    int index = elements.indexOf(parent);
                    Object type = parent.getAttributes().getAttribute(HTML.Attribute.TYPE);
                    Object startObject = parent.getAttributes().getAttribute(HTML.Attribute.START);
                    int start = startObject == null ? 0
                            : Math.max(0, Integer.valueOf(startObject.toString()) - 1);
                    String suffix = "";

                    ++orderedListIndex[index];

                    if (type != null) {
                        switch (((String) type).charAt(0)) {
                        case 'A':
                            suffix = getOLBulletChars(orderedListIndex[index] + start, true);
                            break;
                        case 'a':
                            suffix = getOLBulletChars(orderedListIndex[index] + start, false);
                            break;
                        case 'I':
                            suffix = JRStringUtil.getRomanNumeral(orderedListIndex[index] + start, true);
                            break;
                        case 'i':
                            suffix = JRStringUtil.getRomanNumeral(orderedListIndex[index] + start, false);
                            break;
                        case '1':
                        default:
                            suffix = String.valueOf(orderedListIndex[index] + start);
                            break;
                        }
                    } else {
                        suffix += orderedListIndex[index] + start;
                    }
                    chunk = whitespaces[index] + suffix + DEFAULT_BULLET_SEPARATOR + "  ";

                } else {
                    chunk = whitespaces[elements.indexOf(parent)] + DEFAULT_BULLET_CHARACTER + "  ";
                }
                crtOffset += chunk.length();
            } else if (element instanceof LeafElement) {
                if (element instanceof RunElement) {
                    RunElement runElement = (RunElement) element;
                    AttributeSet attrSet = (AttributeSet) runElement.getAttribute(Tag.A);
                    if (attrSet != null) {
                        hyperlink = new JRBasePrintHyperlink();
                        hyperlink.setHyperlinkType(HyperlinkTypeEnum.REFERENCE);
                        hyperlink.setHyperlinkReference((String) attrSet.getAttribute(HTML.Attribute.HREF));
                        hyperlink.setLinkTarget((String) attrSet.getAttribute(HTML.Attribute.TARGET));
                    }
                }
                try {
                    chunk = document.getText(startOffset, endOffset - startOffset);
                } catch (BadLocationException e) {
                    if (log.isDebugEnabled()) {
                        log.debug("Error converting markup.", e);
                    }
                }
            }
        }
    }

    if (chunk != null) {
        if (!"\n".equals(chunk)) {
            text.append(chunk);
            Map<Attribute, Object> styleAttributes = getAttributes(element.getAttributes());
            if (hyperlink != null) {
                styleAttributes.put(JRTextAttribute.HYPERLINK, hyperlink);
                hyperlink = null;
            }
            if (!styleAttributes.isEmpty()) {
                styleRuns.add(
                        new JRStyledText.Run(styleAttributes, startOffset + crtOffset, endOffset + crtOffset));
            }
        } else {
            //final newline, not appending
            //check if there's any style run that would have covered it, that can happen if there's a <li> tag with style
            int length = text.length();
            for (ListIterator<JRStyledText.Run> it = styleRuns.listIterator(); it.hasNext();) {
                JRStyledText.Run run = it.next();
                //only looking at runs that end at the position where the newline should have been
                //we don't want to hide bugs in which runs that span after the text length are created
                if (run.endIndex == length + 1) {
                    if (run.startIndex < run.endIndex - 1) {
                        it.set(new JRStyledText.Run(run.attributes, run.startIndex, run.endIndex - 1));
                    } else {
                        it.remove();
                    }
                }
            }
        }
    }

    JRStyledText styledText = new JRStyledText(null, text.toString());
    for (JRStyledText.Run run : styleRuns) {
        styledText.addRun(run);
    }
    styledText.setGlobalAttributes(new HashMap<Attribute, Object>());

    return JRStyledTextParser.getInstance().write(styledText);
}

From source file:org.alex73.skarynka.scan.ui.book.PagePopupMenu.java

String showPageNumberDialog() {
    StringBuilder result = new StringBuilder();
    PageNumber dialog = new PageNumber(DataStorage.mainFrame, true);
    dialog.setTitle(Messages.getString("PAGE_NUMBER_TITLE", Book2.simplifyPageNumber(startSelection)));
    dialog.errorLabel.setText(" ");
    dialog.renameButton.addActionListener(new ActionListener() {
        @Override/*w  w  w. java2  s.co m*/
        public void actionPerformed(ActionEvent e) {
            result.append(dialog.txtNumber.getText().trim());
            dialog.dispose();
        }
    });

    dialog.txtNumber.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            check(e.getDocument());
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            check(e.getDocument());
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            check(e.getDocument());
        }

        void check(Document d) {
            dialog.errorLabel.setText(" ");
            try {
                String newText = d.getText(0, d.getLength()).trim();
                newText = Book2.formatPageNumber(newText);
                if (StringUtils.isEmpty(newText)) {
                    dialog.renameButton.setEnabled(false);
                    dialog.errorLabel.setText(Messages.getString("PAGE_NUMBER_ERROR_WRONG"));
                } else {
                    Book2.PageInfo pi = book.getPageInfo(newText);
                    if (pi != null) {
                        dialog.renameButton.setEnabled(false);
                        dialog.errorLabel.setText(Messages.getString("PAGE_NUMBER_ERROR_EXIST",
                                Book2.simplifyPageNumber(newText)));
                    } else {
                        dialog.renameButton.setEnabled(true);
                    }
                }
            } catch (BadLocationException ex) {
                dialog.renameButton.setEnabled(false);
            }
        }
    });

    dialog.setLocationRelativeTo(DataStorage.mainFrame);
    dialog.setVisible(true);
    return result.toString();
}

From source file:org.apache.syncope.ide.netbeans.view.ResourceExplorerTopComponent.java

private void saveContent() {
    try {/*from   w  w  w  .  j a v  a  2s.  c o  m*/
        JTextComponent ed = EditorRegistry.lastFocusedComponent();
        Document document = ed.getDocument();
        String content = document.getText(0, document.getLength());
        String path = (String) document.getProperty(Document.TitleProperty);
        String[] temp = path.split(File.separator);
        String name = temp[temp.length - 1];
        String templateType = temp[temp.length - 2];
        temp = name.split("\\.");
        String format = temp[1];
        String key = temp[0];

        if (templateType.equals("Mail")) {
            if (format.equals("txt")) {
                mailTemplateManagerService.setFormat(key, MailTemplateFormat.TEXT,
                        IOUtils.toInputStream(content, encodingPattern));
            } else {
                mailTemplateManagerService.setFormat(key, MailTemplateFormat.HTML,
                        IOUtils.toInputStream(content, encodingPattern));
            }
        } else if (format.equals("html")) {
            reportTemplateManagerService.setFormat(key, ReportTemplateFormat.HTML,
                    IOUtils.toInputStream(content, encodingPattern));
        } else if (format.equals("fo")) {
            reportTemplateManagerService.setFormat(key, ReportTemplateFormat.FO,
                    IOUtils.toInputStream(content, encodingPattern));
        } else {
            reportTemplateManagerService.setFormat(key, ReportTemplateFormat.CSV,
                    IOUtils.toInputStream(content, encodingPattern));
        }
    } catch (BadLocationException e) {
        Exceptions.printStackTrace(e);
    }
}

From source file:org.debux.webmotion.netbeans.javacc.lexer.impl.LexerUtils.java

public static String getText(Document document, OffsetRange range) throws BadLocationException {
    int start = range.getStart();
    int length = range.getEnd() - start;
    String target = document.getText(start, length);
    return target;
}