Example usage for javax.swing.text Element getElementCount

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

Introduction

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

Prototype

public int getElementCount();

Source Link

Document

Gets the number of child elements contained by this element.

Usage

From source file:net.team2xh.crt.gui.editor.EditorTextPane.java

/**
 * Returns the first character offset of the given line number.
 *
 * @param line Line number./*from  w  w w. j  a va 2s  .co  m*/
 * @return First character offset of that line.
 * @throws BadLocationException
 */
public int getLineStartOffset(int line) throws BadLocationException {
    Element map = doc.getDefaultRootElement();
    if (line < 0) {
        throw new BadLocationException("Negative line", -1);
    } else if (line >= map.getElementCount()) {
        throw new BadLocationException("No such line", doc.getLength() + 1);
    } else {
        Element lineElem = map.getElement(line);
        return lineElem.getStartOffset();
    }
}

From source file:net.team2xh.crt.gui.editor.EditorTextPane.java

/**
 * Returns the last character offset of the given line number.
 *
 * @param line Line number.//from  w  w  w .  j  ava 2s  .  c o  m
 * @return Last character offset of that line.
 * @throws BadLocationException
 */
public int getLineEndOffset(int line) throws BadLocationException {
    Element map = doc.getDefaultRootElement();
    if (line < 0) {
        throw new BadLocationException("Negative line", -1);
    } else if (line >= map.getElementCount()) {
        throw new BadLocationException("No such line", doc.getLength() + 1);
    } else {
        Element lineElem = map.getElement(line);
        return lineElem.getEndOffset();
    }
}

From source file:org.alder.fotobuchconvert.scribus.RtfToScribusConverter.java

void output(XmlBuilder xml, DefaultStyledDocument doc, ScribusWriter scribus) {
    log.debug("Starting conversion of RTF data");
    if (log.isTraceEnabled())
        doc.dump(System.err);//from w w  w . j av a2s .c o m

    try {
        Element section = doc.getDefaultRootElement();
        log.trace(section);
        assert section.getName().equals("section");

        final int nj = section.getElementCount();
        for (int j = 0; j < nj; j++) {
            Element paragraph = section.getElement(j);
            log.trace(paragraph);
            assert section.getName().equals("paragraph");

            // boolean firstInPara = true;
            AttributeSet attr = paragraph.getAttributes();
            Integer alignment = (Integer) attr.getAttribute(StyleConstants.Alignment);

            boolean elementsInThisLine = false;
            final int ni = paragraph.getElementCount();
            for (int i = 0; i < ni; i++) {
                Element content = paragraph.getElement(i);
                assert section.getName().equals("content");

                int start = content.getStartOffset();
                int end = content.getEndOffset();

                attr = content.getAttributes();
                Boolean italic = (Boolean) attr.getAttribute(StyleConstants.Italic);
                Boolean bold = (Boolean) attr.getAttribute(StyleConstants.Bold);
                Boolean underline = (Boolean) attr.getAttribute(StyleConstants.Underline);
                String family = (String) attr.getAttribute(StyleConstants.Family);
                Integer fontSize = (Integer) attr.getAttribute(StyleConstants.Size);
                Color color = (Color) attr.getAttribute(StyleConstants.ColorConstants.Foreground);

                String text = doc.getText(start, end - start);

                // if (firstInPara && text.trim().isEmpty() && family ==
                // null
                // && fontSize == null)
                // continue;
                // else
                // firstInPara = false;
                if (i == ni - 1 && text.trim().isEmpty() && text.length() < 3)
                    continue;
                elementsInThisLine = true;

                while (text.endsWith("\n") || text.endsWith("\r"))
                    text = text.substring(0, text.length() - 1);

                log.debug(italic + " " + bold + " " + underline + " " + family + " " + fontSize + " " + color
                        + "\t\"" + text + "\"");

                XmlBuilder el = xml.add(C.EL_ITEXT).set(C.CH, text);

                if (bold == Boolean.TRUE && italic == Boolean.TRUE)
                    el.set(C.FONT, family + " Bold Italic");
                else if (bold == Boolean.TRUE)
                    el.set(C.FONT, family + " Bold");
                else if (italic == Boolean.TRUE)
                    el.set(C.FONT, family + " Italic");
                else
                    el.set(C.FONT, family + " Regular");

                if (fontSize != null)
                    el.set(C.FONTSIZE, fontSize);

                if (color != null && color.equals(Color.BLACK) && scribus != null) {
                    String colname = scribus.colorManager.getColorName(color);
                    el.set(C.FCOLOR, colname);
                }
            }

            if (!elementsInThisLine && j == nj - 1)
                break; // don't convert last line if empty

            XmlBuilder el = xml.add(C.EL_PARA);
            if (alignment != null)
                switch (alignment) {
                case StyleConstants.ALIGN_LEFT:
                    el.set(C.ALIGN, 0);
                    break;
                case StyleConstants.ALIGN_CENTER:
                    el.set(C.ALIGN, 1);
                    break;
                case StyleConstants.ALIGN_RIGHT:
                    el.set(C.ALIGN, 2);
                    break;
                case StyleConstants.ALIGN_JUSTIFIED:
                    el.set(C.ALIGN, 3);
                    break;
                }
        }
    } catch (BadLocationException e) {
        throw new RuntimeException("This error should not occour", e);
    }

}

From source file:org.deegree.tools.metadata.InspireValidator.java

/**
 * parse INSPIRE metadata validator response and print out result onto the console
 * /*from w  ww .ja va2s . c  o m*/
 * @param response
 * @throws IOException
 * @throws IllegalStateException
 */
private void parseServiceResponse(HttpResponse response) throws Exception {
    String s = FileUtils.readTextFile(((BasicHttpResponse) response).getEntity().getContent()).toString();
    if (response.getStatusLine().getStatusCode() != 200) {
        outputWriter.println(s);
        outputWriter.println();
        return;
    }
    s = "<html><head></head><body>" + s + "</body></html>";
    BufferedReader br = new BufferedReader(new StringReader(s));

    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.IMPLIED))) {
            // 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));
                }
            }
            outputWriter.println(text.toString());
        }
    }
    outputWriter.println("---------------------------------------------------------------------");
    outputWriter.println();
}

From source file:org.domainmath.gui.MainFrame.java

public void gotoLine(String goto_file, int lineRequested) {
    if (fileTab.getSelectedIndex() >= 0) {
        int indexOf = MainFrame.fileNameList.indexOf(goto_file);
        RTextScrollPane t = (RTextScrollPane) fileTab.getComponentAt(indexOf);
        RSyntaxTextArea selectedArea = (RSyntaxTextArea) t.getTextArea();
        try {//ww  w  . j av  a 2 s  .  co  m
            Element element = selectedArea.getDocument().getDefaultRootElement();

            int rowCount = element.getElementCount();
            if (lineRequested > rowCount || lineRequested < 0) {

                setVisible(false);
                return;
            }
            Element row = null;
            int firstCharacter = 0;
            int rowNumber = 0;
            for (int i = 0; i < lineRequested; ++i) {
                firstCharacter = getFirstCharacter(row);
                rowNumber = element.getElementIndex(firstCharacter);
                row = element.getElement(rowNumber);
            }
            int lastColumnInRow = row.getEndOffset();
            selectedArea.select(firstCharacter, lastColumnInRow - 1);

        } catch (Exception e) {

        }
    }
}

From source file:org.domainmath.gui.MainFrame.java

private void gotoItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gotoItemActionPerformed
    if (fileTab.getSelectedIndex() >= 0) {
        String s = JOptionPane.showInputDialog("Line Number:");
        RTextScrollPane t = (RTextScrollPane) fileTab.getComponentAt(fileTab.getSelectedIndex());
        RSyntaxTextArea selectedArea = (RSyntaxTextArea) t.getTextArea();
        try {/*from   www .  j  ava 2s. co m*/
            Element element = selectedArea.getDocument().getDefaultRootElement();
            int lineRequested = Integer.parseInt(s);
            int rowCount = element.getElementCount();
            if (lineRequested > rowCount || lineRequested < 0) {

                setVisible(false);
                return;
            }
            Element row = null;
            int firstCharacter = 0;
            int rowNumber = 0;
            for (int i = 0; i < lineRequested; ++i) {
                firstCharacter = getFirstCharacter(row);
                rowNumber = element.getElementIndex(firstCharacter);
                row = element.getElement(rowNumber);
            }
            int lastColumnInRow = row.getEndOffset();
            selectedArea.select(firstCharacter, lastColumnInRow - 1);

        } catch (Exception e) {

        }
    }
}

From source file:org.fife.rsta.ac.js.JavaScriptParser.java

/**
 * {@inheritDoc}//  ww w.j  a  v  a 2s.  c o  m
 */
public ParseResult parse(RSyntaxDocument doc, String style) {

    astRoot = null;
    result.clearNotices();
    // Always spell check all lines, for now.
    Element root = doc.getDefaultRootElement();
    int lineCount = root.getElementCount();
    result.setParsedLines(0, lineCount - 1);

    DocumentReader r = new DocumentReader(doc);
    ErrorCollector errorHandler = new ErrorCollector();
    long start = System.currentTimeMillis();
    try {
        String script = IOUtils.toString(r);
        CompilerEnvirons env = createCompilerEnvironment(errorHandler, langSupport);
        Parser parser = new Parser(env);
        astRoot = parser.parse(new StringReader(MIRTH_SCRIPT_PREFIX + script + MIRTH_SCRIPT_SUFFIX), null, 0);
        env = createCompilerEnvironment(new ErrorCollector(), langSupport);
        astRoot = new Parser(env).parse(script, null, 0);
        long time = System.currentTimeMillis() - start;
        result.setParseTime(time);
    } catch (IOException ioe) { // Never happens
        result.setError(ioe);
        ioe.printStackTrace();
    } catch (RhinoException re) {
        // Shouldn't happen since we're passing an ErrorCollector in
        int line = re.lineNumber();
        // if (line>0) {
        Element elem = root.getElement(line);
        int offs = elem.getStartOffset();
        int len = elem.getEndOffset() - offs - 1;
        String msg = re.details();
        result.addNotice(new DefaultParserNotice(this, msg, line, offs, len));
        // }
    } catch (Exception e) {
        result.setError(e); // catch all
    }

    r.close();

    // Get any parser errors.
    switch (langSupport.getErrorParser()) {
    default:
    case RHINO:
        gatherParserErrorsRhino(errorHandler, root);
        break;
    case JSHINT:
        gatherParserErrorsJsHint(doc);
        break;
    }

    // addNotices(doc);
    support.firePropertyChange(PROPERTY_AST, null, astRoot);

    return result;

}

From source file:ru.gelin.fictionbook.reader.models.FBSimpleElementTest.java

@Test
public void testGetElementCount() {
    Node node = fb.getDocument().selectSingleNode("//fb:section[@id='section1']");
    int children = node.selectNodes("*[node()]").size();
    Element section = document.getElement(node);
    assertEquals(children, section.getElementCount());
}

From source file:tk.tomby.tedit.core.Buffer.java

/**
 * DOCUMENT ME!//from w  ww  . ja v a  2  s.  c o  m
 *
 * @param line DOCUMENT ME!
 */
public void gotoLine(int line) {
    Element root = editor.getDocument().getDefaultRootElement();

    if ((line < root.getElementCount()) && (line > 0)) {
        Element element = root.getElement(line - 1);
        editor.setCaretPosition(element.getStartOffset());
    }
}