Example usage for javax.swing.text Element getEndOffset

List of usage examples for javax.swing.text Element getEndOffset

Introduction

In this page you can find the example usage for javax.swing.text Element getEndOffset.

Prototype

public int getEndOffset();

Source Link

Document

Fetches the offset from the beginning of the document that this element ends at.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JTextArea textArea = new JTextArea("word1 word2\nword3\nword4");
    Element paragraph = textArea.getDocument().getDefaultRootElement();
    int contentCount = paragraph.getElementCount();
    for (int i = 0; i < contentCount; i++) {
        Element e = paragraph.getElement(i);
        int rangeStart = e.getStartOffset();
        int rangeEnd = e.getEndOffset();
        String line = textArea.getText(rangeStart, rangeEnd - rangeStart);
        System.out.println(line);
    }//  ww  w. j ava2 s  .  co m
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JTextPane textPane = new JTextPane();
    Element section = textPane.getDocument().getDefaultRootElement();

    int paraCount = section.getElementCount();

    for (int i = 0; i < paraCount; i++) {
        Element e = section.getElement(i);
        int rangeStart = e.getStartOffset();
        int rangeEnd = e.getEndOffset();

        String para = textPane.getText(rangeStart, rangeEnd - rangeStart);
        System.out.println(para);
    }/*  w  ww  . j  a va2s  .c om*/
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JTextArea textArea = new JTextArea("word1 word2\nword3\nword4");
    Document doc = textArea.getDocument();
    ElementIterator it = new ElementIterator(doc.getDefaultRootElement());
    Element e;
    while ((e = it.next()) != null) {
        if (e.isLeaf()) {
            int rangeStart = e.getStartOffset();
            int rangeEnd = e.getEndOffset();

            String line = textArea.getText(rangeStart, rangeEnd - rangeStart);
            System.out.println(line);
        }// w w  w  .  j  av  a2s.  c om
    }
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.java2s.com");
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);/*from  w  w  w. j  a v  a  2  s .  c o  m*/

    ElementIterator iterator = new ElementIterator(htmlDoc);
    Element element;
    while ((element = iterator.next()) != null) {
        AttributeSet attributes = element.getAttributes();
        Object name = attributes.getAttribute(StyleConstants.NameAttribute);
        if ((name instanceof HTML.Tag) && (name == HTML.Tag.H1)) {
            StringBuffer text = new StringBuffer();
            int count = element.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = element.getElement(i);
                AttributeSet childAttributes = child.getAttributes();
                if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    int startOffset = child.getStartOffset();
                    int endOffset = child.getEndOffset();
                    int length = endOffset - startOffset;
                    text.append(htmlDoc.getText(startOffset, length));
                }
            }
            System.out.println(name + ": " + text.toString());
        }
    }
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);/*from  www. j a va  2s  .co  m*/

    Element element;
    ElementIterator iterator = new ElementIterator(htmlDoc);
    while ((element = iterator.next()) != null) {
        AttributeSet attributes = element.getAttributes();
        Object name = attributes.getAttribute(StyleConstants.NameAttribute);

        if ((name instanceof HTML.Tag) && (name == HTML.Tag.H1 || name == HTML.Tag.H2 || name == HTML.Tag.P)) {
            // Build up content text as it may be within multiple elements
            int count = element.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = element.getElement(i);
                AttributeSet childAttributes = child.getAttributes();
                if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    int startOffset = child.getStartOffset();
                    int endOffset = child.getEndOffset();
                    int length = endOffset - startOffset;
                    System.out.println(htmlDoc.getText(startOffset, length));
                }
            }
        }
    }
}

From source file:ElementIteratorExample.java

public static void main(String args[]) throws Exception {

    if (args.length != 1) {
        System.err.println("Usage: java ElementIteratorExample input-URL");
    }/*from  www.  j  a  va  2  s  .com*/

    // Load HTML file synchronously
    URL url = new URL(args[0]);
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);

    // Parse
    ElementIterator iterator = new ElementIterator(htmlDoc);
    Element element;
    while ((element = iterator.next()) != null) {
        AttributeSet attributes = element.getAttributes();
        Object name = attributes.getAttribute(StyleConstants.NameAttribute);
        if ((name instanceof HTML.Tag)
                && ((name == HTML.Tag.H1) || (name == HTML.Tag.H2) || (name == HTML.Tag.H3))) {
            // Build up content text as it may be within multiple elements
            StringBuffer text = new StringBuffer();
            int count = element.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = element.getElement(i);
                AttributeSet childAttributes = child.getAttributes();
                if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    int startOffset = child.getStartOffset();
                    int endOffset = child.getEndOffset();
                    int length = endOffset - startOffset;
                    text.append(htmlDoc.getText(startOffset, length));
                }
            }
            System.out.println(name + ": " + text.toString());
        }
    }
    System.exit(0);
}

From source file:Main.java

private static final Element getLineElem(Document d, int offs) {
    Element map = d.getDefaultRootElement();
    int index = map.getElementIndex(offs);
    Element elem = map.getElement(index);
    if ((offs >= elem.getStartOffset()) && (offs < elem.getEndOffset())) {
        return elem;
    }/*from   ww  w  .ja v a 2 s  . co m*/
    return null;
}

From source file:com.keevosh.springframework.boot.netbeans.SpringBootConfigurationCompletionProvider.java

static int getRowFirstNonWhite(StyledDocument doc, int offset) throws BadLocationException {
    Element lineElement = doc.getParagraphElement(offset);
    int start = lineElement.getStartOffset();
    while (start + 1 < lineElement.getEndOffset()) {
        try {//from  w  ww  .j a  v  a 2  s.com
            if (doc.getText(start, 1).charAt(0) != ' ') {
                break;
            }
        } catch (BadLocationException ex) {
            throw (BadLocationException) new BadLocationException(
                    "calling getText(" + start + ", " + (start + 1) + ") on doc of length: " + doc.getLength(),
                    start).initCause(ex);
        }
        start++;
    }
    return start;
}

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   w w w.ja va2s . co m
 */
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:ShowHTMLViews.java

public static void displayElement(Document doc, Element e, int indent, PrintStream out) {
    for (int i = 0; i < indent; i++) {
        out.print("  ");
    }//from w w w. j a va2 s .c  om
    out.println("===== Element Class: " + getShortClassName(e.getClass()));
    for (int i = 0; i < indent; i++) {
        out.print("  ");
    }
    int startOffset = e.getStartOffset();
    int endOffset = e.getEndOffset();
    out.println("Offsets [" + startOffset + ", " + endOffset + "]");
    AttributeSet a = e.getAttributes();
    Enumeration x = a.getAttributeNames();
    for (int i = 0; i < indent; i++) {
        out.print("  ");
    }
    out.println("ATTRIBUTES:");
    while (x.hasMoreElements()) {
        for (int i = 0; i < indent; i++) {
            out.print("  ");
        }
        Object attr = x.nextElement();
        out.println(" (" + attr + ", " + a.getAttribute(attr) + ")" + " [" + getShortClassName(attr.getClass())
                + "/" + getShortClassName(a.getAttribute(attr).getClass()) + "] ");
    }

    // Display the text for a leaf element
    if (e.isLeaf()) {
        try {
            String str = doc.getText(startOffset, endOffset - startOffset);
            if (str.length() > 40) {
                str = str.substring(0, 40);
            }
            if (str.length() > 0) {
                for (int i = 0; i < indent; i++) {
                    out.print("  ");
                }
                out.println("[" + str + "]");
            }
        } catch (BadLocationException ex) {
        }
    }

    // Display child elements
    int count = e.getElementCount();
    for (int i = 0; i < count; i++) {
        displayElement(doc, e.getElement(i), indent + 1, out);
    }
}