Example usage for javax.swing.text AttributeSet getAttribute

List of usage examples for javax.swing.text AttributeSet getAttribute

Introduction

In this page you can find the example usage for javax.swing.text AttributeSet getAttribute.

Prototype

public Object getAttribute(Object key);

Source Link

Document

Fetches the value of the given attribute.

Usage

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

/**
 * Searches the specified element for CLASS attribute setting
 *//*from  w ww .j  ava2  s . c  o  m*/
private String findStyle(Element element) {
    AttributeSet as = element.getAttributes();
    if (as == null) {
        return null;
    }
    Object val = as.getAttribute(HTML.Attribute.CLASS);
    if (val != null && (val instanceof String)) {
        return (String) val;
    }
    for (Enumeration e = as.getAttributeNames(); e.hasMoreElements();) {
        Object key = e.nextElement();
        if (key instanceof HTML.Tag) {
            AttributeSet eas = (AttributeSet) (as.getAttribute(key));
            if (eas != null) {
                val = eas.getAttribute(HTML.Attribute.CLASS);
                if (val != null) {
                    return (String) val;
                }
            }
        }

    }
    return null;
}

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

/**
 * Handles caret tracking and related events, such as displaying the current
 * style of the text under the caret/*from  w w  w  .j  ava  2 s . c o  m*/
 */
private void handleCaretPositionChange(CaretEvent ce) {
    int caretPos = ce.getDot();
    Element element = htmlDoc.getCharacterElement(caretPos);
    /*
     * //---- TAG EXPLICATOR CODE
     * -------------------------------------------
     * javax.swing.text.ElementIterator ei = new
     * javax.swing.text.ElementIterator(htmlDoc); Element ele; while((ele =
     * ei.next()) != null) { log.debug("ELEMENT : " + ele.getName()); }
     * log.debug("ELEMENT:" + element.getName()); Element elementParent =
     * element.getParentElement(); log.debug("ATTRS:"); AttributeSet attribs
     * = elementParent.getAttributes(); for(Enumeration eAttrs =
     * attribs.getAttributeNames(); eAttrs.hasMoreElements();) {
     * log.debug("  " + eAttrs.nextElement().toString()); }
     * while(elementParent != null &&
     * !elementParent.getName().equals("body")) { String parentName =
     * elementParent.getName(); log.debug("PARENT:" + parentName);
     * log.debug("ATTRS:"); attribs = elementParent.getAttributes();
     * for(Enumeration eAttr = attribs.getAttributeNames();
     * eAttr.hasMoreElements();) { log.debug("  " +
     * eAttr.nextElement().toString()); } elementParent =
     * elementParent.getParentElement(); } //---- END
     * -------------------------------------------
     */
    if (jtpMain.hasFocus()) {
        if (element == null) {
            return;
        }
        String style = null;
        Vector<Element> vcStyles = new Vector<Element>();
        while (element != null) {
            if (style == null) {
                style = findStyle(element);
            }
            vcStyles.add(element);
            element = element.getParentElement();
        }
        int stylefound = -1;
        if (style != null) {
            for (int i = 0; i < jcmbStyleSelector.getItemCount(); i++) {
                String in = (String) (jcmbStyleSelector.getItemAt(i));
                if (in.equalsIgnoreCase(style)) {
                    stylefound = i;
                    break;
                }
            }
        }
        if (stylefound > -1) {
            jcmbStyleSelector.getAction().setEnabled(false);
            jcmbStyleSelector.setSelectedIndex(stylefound);
            jcmbStyleSelector.getAction().setEnabled(true);
        } else {
            jcmbStyleSelector.setSelectedIndex(0);
        }
        // see if current font face is set
        if (jcmbFontSelector != null && jcmbFontSelector.isVisible()) {
            AttributeSet mainAttrs = jtpMain.getCharacterAttributes();
            Enumeration e = mainAttrs.getAttributeNames();
            Object activeFontName = (Object) (Translatrix.getTranslationString("SelectorToolFontsDefaultFont"));
            while (e.hasMoreElements()) {
                Object nexte = e.nextElement();
                if (nexte.toString().toLowerCase().equals("face")
                        || nexte.toString().toLowerCase().equals("font-family")) {
                    activeFontName = mainAttrs.getAttribute(nexte);
                    break;
                }
            }
            jcmbFontSelector.getAction().setEnabled(false);
            jcmbFontSelector.getModel().setSelectedItem(activeFontName);
            jcmbFontSelector.getAction().setEnabled(true);
        }
    }
}

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

public void actionPerformed(ActionEvent ae) {
    try {// www  .  j a v a2  s.  co m
        String command = ae.getActionCommand();
        if (command.equals(CMD_DOC_NEW) || command.equals(CMD_DOC_NEW_STYLED)) {
            SimpleInfoDialog sidAsk = new SimpleInfoDialog(this.getWindow(), "", true,
                    Translatrix.getTranslationString("AskNewDocument"), SimpleInfoDialog.QUESTION);
            String decision = sidAsk.getDecisionValue();
            if (decision.equals(Translatrix.getTranslationString("DialogAccept"))) {
                if (styleSheet != null && command.equals(CMD_DOC_NEW_STYLED)) {
                    htmlDoc = new ExtendedHTMLDocument(styleSheet);
                } else {
                    htmlDoc = (ExtendedHTMLDocument) (htmlKit.createDefaultDocument());
                    htmlDoc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
                    htmlDoc.setPreservesUnknownTags(preserveUnknownTags);
                }
                registerDocument(htmlDoc);
                jtpSource.setText(jtpMain.getText());
                currentFile = null;
                updateTitle();
            }
        } else if (command.equals(CMD_DOC_OPEN_HTML)) {
            openDocument(null);
        } else if (command.equals(CMD_DOC_OPEN_CSS)) {
            openStyleSheet(null);
        } else if (command.equals(CMD_DOC_SAVE)) {
            writeOut((HTMLDocument) (jtpMain.getDocument()), currentFile);
            updateTitle();
        } else if (command.equals(CMD_DOC_SAVE_AS)) {
            writeOut((HTMLDocument) (jtpMain.getDocument()), null);
        } else if (command.equals(CMD_DOC_SAVE_BODY)) {
            writeOutFragment((HTMLDocument) (jtpMain.getDocument()), "body");
        } else if (command.equals(CMD_DOC_SAVE_RTF)) {
            writeOutRTF((StyledDocument) (jtpMain.getStyledDocument()));
        } else if (command.equals(CMD_CLIP_CUT)) {
            if (sourceWindowActive && jtpSource.hasFocus()) {
                jtpSource.cut();
            } else {
                jtpMain.cut();
            }
        } else if (command.equals(CMD_CLIP_COPY)) {
            if (sourceWindowActive && jtpSource.hasFocus()) {
                jtpSource.copy();
            } else {
                jtpMain.copy();
            }
        } else if (command.equals(CMD_CLIP_PASTE)) {
            if (!jspSource.isShowing()) {
                jtpMain.paste();
            }
        } else if (command.equals(CMD_CLIP_PASTE_PLAIN)) {
            if (!jspSource.isShowing()) {
                try {
                    if (sysClipboard != null) {
                        jtpMain.getDocument().insertString(jtpMain.getCaretPosition(),
                                sysClipboard.getData(dfPlainText).toString(), (AttributeSet) null);
                    } else {
                        jtpMain.getDocument()
                                .insertString(
                                        jtpMain.getCaretPosition(), Toolkit.getDefaultToolkit()
                                                .getSystemClipboard().getData(dfPlainText).toString(),
                                        (AttributeSet) null);
                    }
                    refreshOnUpdate();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        } else if (command.equals(CMD_DOC_PRINT)) {
            DocumentRenderer dr = new DocumentRenderer();
            dr.print(htmlDoc);

        } else if (command.equals(CMD_DEBUG_DESCRIBE_DOC)) {
            log.debug("------------DOCUMENT------------");
            log.debug("Content Type : " + jtpMain.getContentType());
            log.debug("Editor Kit   : " + jtpMain.getEditorKit());
            log.debug("Doc Tree     :");
            log.debug("");
            describeDocument(jtpMain.getStyledDocument());
            log.debug("--------------------------------");
            log.debug("");
        } else if (command.equals(CMD_DEBUG_DESCRIBE_CSS)) {
            log.debug("-----------STYLESHEET-----------");
            log.debug("Stylesheet Rules");
            Enumeration rules = styleSheet.getStyleNames();
            while (rules.hasMoreElements()) {
                String ruleName = (String) (rules.nextElement());
                Style styleRule = styleSheet.getStyle(ruleName);
                log.debug(styleRule.toString());
            }
            log.debug("--------------------------------");
            log.debug("");
        } else if (command.equals(CMD_DEBUG_CURRENT_TAGS)) {
            log.debug("Caret Position : " + jtpMain.getCaretPosition());
            AttributeSet attribSet = jtpMain.getCharacterAttributes();
            Enumeration attribs = attribSet.getAttributeNames();
            log.debug("Attributes     : ");
            while (attribs.hasMoreElements()) {
                String attribName = attribs.nextElement().toString();
                log.debug("                 " + attribName + " | " + attribSet.getAttribute(attribName));
            }
        } else if (command.equals(CMD_TOGGLE_TOOLBAR_SINGLE)) {
            jToolBar.setVisible(jcbmiViewToolbar.isSelected());
        } else if (command.equals(CMD_TOGGLE_TOOLBAR_MAIN)) {
            jToolBarMain.setVisible(jcbmiViewToolbarMain.isSelected());
        } else if (command.equals(CMD_TOGGLE_TOOLBAR_FORMAT)) {
            jToolBarFormat.setVisible(jcbmiViewToolbarFormat.isSelected());
        } else if (command.equals(CMD_TOGGLE_TOOLBAR_STYLES)) {
            jToolBarStyles.setVisible(jcbmiViewToolbarStyles.isSelected());
        } else if (command.equals(CMD_TOGGLE_SOURCE_VIEW)) {
            toggleSourceWindow();
        } else if (command.equals(CMD_DOC_SERIALIZE_OUT)) {
            serializeOut((HTMLDocument) (jtpMain.getDocument()));
        } else if (command.equals(CMD_DOC_SERIALIZE_IN)) {
            serializeIn();
        } else if (command.equals(CMD_TABLE_INSERT)) {
            tableCtl.insertTable();
        } else if (command.equals(CMD_TABLE_DELETE)) {
            tableCtl.deleteTable();
        } else if (command.equals(CMD_TABLE_EDIT)) {
            tableCtl.editTable();
        } else if (command.equals(CMD_TABLE_CELL_EDIT)) {
            tableCtl.editCell();
        } else if (command.equals(CMD_TABLE_ROW_INSERT)) {
            tableCtl.insertTableRow(false);
        } else if (command.equals(CMD_TABLE_ROW_INSERT_AFTER)) {
            tableCtl.insertTableRow(true);
        } else if (command.equals(CMD_TABLE_COLUMN_INSERT)) {
            tableCtl.insertTableColumn(false);
        } else if (command.equals(CMD_TABLE_COLUMN_INSERT_AFTER)) {
            tableCtl.insertTableColumn(true);
        } else if (command.equals(CMD_TABLE_ROW_DELETE)) {
            tableCtl.deleteTableRow();
        } else if (command.equals(CMD_TABLE_COLUMN_DELETE)) {
            tableCtl.deleteTableColumn();
        } else if (command.equals(CMD_TABLE_COLUMN_FORMAT)) {
            tableCtl.formatTableColumn();
        } else if (command.equals(CMD_INSERT_BREAK)) {
            insertBreak();
        } else if (command.equals(CMD_INSERT_NBSP)) {
            insertNonbreakingSpace();
        } else if (command.equals(CMD_INSERT_HR)) {
            insertHR();
        } else if (command.equals(CMD_INSERT_IMAGE_LOCAL)) {
            insertLocalImage(null);
        } else if (command.equals(CMD_INSERT_IMAGE_URL)) {
            insertURLImage();
        } else if (command.equals(CMD_INSERT_UNICODE_CHAR)) {
            insertUnicode(UnicodeDialog.UNICODE_BASE);
        } else if (command.equals(CMD_INSERT_UNICODE_MATH)) {
            insertUnicode(UnicodeDialog.UNICODE_MATH);
        } else if (command.equals(CMD_INSERT_UNICODE_DRAW)) {
            insertUnicode(UnicodeDialog.UNICODE_DRAW);
        } else if (command.equals(CMD_INSERT_UNICODE_DING)) {
            insertUnicode(UnicodeDialog.UNICODE_DING);
        } else if (command.equals(CMD_INSERT_UNICODE_SIGS)) {
            insertUnicode(UnicodeDialog.UNICODE_SIGS);
        } else if (command.equals(CMD_INSERT_UNICODE_SPEC)) {
            insertUnicode(UnicodeDialog.UNICODE_SPEC);
        } else if (command.equals(CMD_FORM_INSERT)) {
            String[] fieldNames = { "name", "method", "enctype" };
            String[] fieldTypes = { "text", "combo", "text" };
            String[] fieldValues = { "", "POST,GET", "text" };
            insertFormElement(HTML.Tag.FORM, "form", (Hashtable) null, fieldNames, fieldTypes, fieldValues,
                    true);
        } else if (command.equals(CMD_FORM_TEXTFIELD)) {
            Hashtable<String, String> htAttribs = new Hashtable<String, String>();
            htAttribs.put("type", "text");
            String[] fieldNames = { "name", "value", "size", "maxlength" };
            String[] fieldTypes = { "text", "text", "text", "text" };
            insertFormElement(HTML.Tag.INPUT, "input", htAttribs, fieldNames, fieldTypes, false);
        } else if (command.equals(CMD_FORM_TEXTAREA)) {
            String[] fieldNames = { "name", "rows", "cols" };
            String[] fieldTypes = { "text", "text", "text" };
            insertFormElement(HTML.Tag.TEXTAREA, "textarea", (Hashtable) null, fieldNames, fieldTypes, true);
        } else if (command.equals(CMD_FORM_CHECKBOX)) {
            Hashtable<String, String> htAttribs = new Hashtable<String, String>();
            htAttribs.put("type", "checkbox");
            String[] fieldNames = { "name", "checked" };
            String[] fieldTypes = { "text", "bool" };
            insertFormElement(HTML.Tag.INPUT, "input", htAttribs, fieldNames, fieldTypes, false);
        } else if (command.equals(CMD_FORM_RADIO)) {
            Hashtable<String, String> htAttribs = new Hashtable<String, String>();
            htAttribs.put("type", "radio");
            String[] fieldNames = { "name", "checked" };
            String[] fieldTypes = { "text", "bool" };
            insertFormElement(HTML.Tag.INPUT, "input", htAttribs, fieldNames, fieldTypes, false);
        } else if (command.equals(CMD_FORM_PASSWORD)) {
            Hashtable<String, String> htAttribs = new Hashtable<String, String>();
            htAttribs.put("type", "password");
            String[] fieldNames = { "name", "value", "size", "maxlength" };
            String[] fieldTypes = { "text", "text", "text", "text" };
            insertFormElement(HTML.Tag.INPUT, "input", htAttribs, fieldNames, fieldTypes, false);
        } else if (command.equals(CMD_FORM_BUTTON)) {
            Hashtable<String, String> htAttribs = new Hashtable<String, String>();
            htAttribs.put("type", "button");
            String[] fieldNames = { "name", "value" };
            String[] fieldTypes = { "text", "text" };
            insertFormElement(HTML.Tag.INPUT, "input", htAttribs, fieldNames, fieldTypes, false);
        } else if (command.equals(CMD_FORM_SUBMIT)) {
            Hashtable<String, String> htAttribs = new Hashtable<String, String>();
            htAttribs.put("type", "submit");
            String[] fieldNames = { "name", "value" };
            String[] fieldTypes = { "text", "text" };
            insertFormElement(HTML.Tag.INPUT, "input", htAttribs, fieldNames, fieldTypes, false);
        } else if (command.equals(CMD_FORM_RESET)) {
            Hashtable<String, String> htAttribs = new Hashtable<String, String>();
            htAttribs.put("type", "reset");
            String[] fieldNames = { "name", "value" };
            String[] fieldTypes = { "text", "text" };
            insertFormElement(HTML.Tag.INPUT, "input", htAttribs, fieldNames, fieldTypes, false);
        } else if (command.equals(CMD_SEARCH_FIND)) {
            doSearch((String) null, (String) null, false, lastSearchCaseSetting, lastSearchTopSetting);
        } else if (command.equals(CMD_SEARCH_FIND_AGAIN)) {
            doSearch(lastSearchFindTerm, (String) null, false, lastSearchCaseSetting, false);
        } else if (command.equals(CMD_SEARCH_REPLACE)) {
            doSearch((String) null, (String) null, true, lastSearchCaseSetting, lastSearchTopSetting);
        } else if (command.equals(CMD_EXIT)) {
            this.dispose();
        } else if (command.equals(CMD_HELP_ABOUT)) {
            new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("About"), true,
                    Translatrix.getTranslationString("AboutMessage"), SimpleInfoDialog.INFO);
        } else if (command.equals(CMD_ENTER_PARAGRAPH)) {
            setEnterKeyIsBreak(false);
        } else if (command.equals(CMD_ENTER_BREAK)) {
            setEnterKeyIsBreak(true);
        } else if (command.equals(CMD_SPELLCHECK)) {
            checkDocumentSpelling(jtpMain.getDocument());
        } else if (command.equals(CMD_MAXIMIZE)) {
            if (maximizeHandler != null) {
                if (maximized) {
                    maximizeHandler.minimize();
                    jbtnMaximize.setToolTipText(Translatrix.getTranslationString("Maximize"));
                } else {
                    maximizeHandler.maximize();
                    jbtnMaximize.setToolTipText(Translatrix.getTranslationString("Restore"));
                }
                maximized = !maximized;
            }
        }
    } catch (IOException ioe) {
        logException("IOException in actionPerformed method", ioe);
        new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("Error"), true,
                Translatrix.getTranslationString("ErrorIOException"), SimpleInfoDialog.ERROR);
    } catch (BadLocationException ble) {
        logException("BadLocationException in actionPerformed method", ble);
        new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("Error"), true,
                Translatrix.getTranslationString("ErrorBadLocationException"), SimpleInfoDialog.ERROR);
    } catch (NumberFormatException nfe) {
        logException("NumberFormatException in actionPerformed method", nfe);
        new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("Error"), true,
                Translatrix.getTranslationString("ErrorNumberFormatException"), SimpleInfoDialog.ERROR);
    } catch (ClassNotFoundException cnfe) {
        logException("ClassNotFound Exception in actionPerformed method", cnfe);
        new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("Error"), true,
                Translatrix.getTranslationString("ErrorClassNotFoundException "), SimpleInfoDialog.ERROR);
    } catch (RuntimeException re) {
        logException("RuntimeException in actionPerformed method", re);
        new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("Error"), true,
                Translatrix.getTranslationString("ErrorRuntimeException"), SimpleInfoDialog.ERROR);
    }
}

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  ww w  .j a v  a  2s  . 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  w  w . j a  v  a  2 s .co 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.jets3t.gui.JHtmlLabel.java

/**
 * Triggers the listener to follow an HTML href link that has been clicked.
 *
 * @param e event/* w ww  . java  2s.c  om*/
 */
public void mouseClicked(MouseEvent e) {
    AccessibleJLabel acc = (AccessibleJLabel) getAccessibleContext();
    int stringIndexAtPoint = acc.getIndexAtPoint(e.getPoint());
    if (stringIndexAtPoint < 0) {
        return;
    }
    AttributeSet attr = (AttributeSet) acc.getCharacterAttribute(acc.getIndexAtPoint(e.getPoint()))
            .getAttribute(HTML.Tag.A);
    if (attr != null) {
        String href = (String) attr.getAttribute(HTML.Attribute.HREF);
        String target = (String) attr.getAttribute(HTML.Attribute.TARGET);
        try {
            if (listener == null) {
                log.warn("No HyperlinkActivatedListener available to follow HTML link for label: " + getText());
            } else {
                listener.followHyperlink(new URL(href), target);
            }
        } catch (Exception ex) {
            log.error("Unable to load URL: " + href, ex);
        }
    }
}

From source file:org.jets3t.gui.JHtmlLabel.java

/**
 * Changes the mouse cursor to a hand to indicate when the mouse moves over a clickable
 * HTML link.//from  w  w w . jav  a2 s.co  m
 *
 * @param e event
 */
public void mouseMoved(MouseEvent e) {
    AccessibleJLabel acc = (AccessibleJLabel) getAccessibleContext();
    int stringIndexAtPoint = acc.getIndexAtPoint(e.getPoint());
    if (stringIndexAtPoint < 0) {
        return;
    }
    javax.swing.text.AttributeSet attr = acc.getCharacterAttribute(stringIndexAtPoint);
    if (attr.getAttribute(HTML.Tag.A) == null) {
        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    } else {
        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    }
}

From source file:org.pmedv.core.components.RelativeImageView.java

/**
 * Method looks up an integer-valued attribute (not recursive!)
 * // w  w  w.  ja v  a2s  .c o  m
 * @param name
 *            HTML.Attribute name
 * @param iDefault
 *            default int value
 * @return returns int value of the given attribute or the default if the
 *         given attribute was not found.
 */
private int getIntAttr(HTML.Attribute name, int iDefault) {

    AttributeSet myAttr = fElement.getAttributes();
    if (myAttr.isDefined(name)) {
        int i;
        String val = (String) myAttr.getAttribute(name);
        if (val == null) {
            i = iDefault;
        } else {
            try {
                i = Math.max(0, Integer.parseInt(val));
            } catch (NumberFormatException nfe) {
                log.debug("setting i to default value.");
                i = iDefault;
            }
        }
        return i;
    } else {
        return iDefault;
    }
}

From source file:tufts.vue.RichTextBox.java

/***********
 *******NOTES FROM FONT EDITOR PANEL TO HELP WITH COPY/PASTE OF STYLES.
globalSizeListener = new ActionListener(){
        //from  w ww . j a v a  2  s . c om
   public void actionPerformed(ActionEvent fe) 
   {
              
      if (suspendItemListeners)
         return;
              
      if (lwtext == null)
         return;
        
      lwtext.richLabelBox.selectAll();
      final String textSize = mSizeField.getSelectedItem().toString();
      SHTMLDocument doc = (SHTMLDocument)lwtext.richLabelBox.getDocument();
      SimpleAttributeSet set = new SimpleAttributeSet();
        Util.styleSheet().addCSSAttribute(set, CSS.Attribute.FONT_SIZE,
                 textSize);
        set.addAttribute(HTML.Attribute.SIZE, textSize);
        lwtext.richLabelBox.applyAttributes(set, false);
                
      lwtext.richLabelBox.select(0,0);
      //lwtext.setLabel0(lwtext.richLabelBox.getRichText(), false);
      lwtext.richLabelBox.setSize(lwtext.richLabelBox.getPreferredSize());                                        
               
          if (lwtext.getParent() !=null)
              lwtext.getParent().layout();                                                  
                 
       lwtext.notify(lwtext.richLabelBox, LWKey.Repaint);                     
               
               
   }
 };
                     
  globalFaceListener = new ActionListener(){ 
     public void actionPerformed(ActionEvent fe) 
     {                
        if (suspendItemListeners)
         return;
              
        if (lwtext == null)
         return;
        lwtext.richLabelBox.selectAll();
      SHTMLDocument doc = (SHTMLDocument)lwtext.richLabelBox.getDocument();
      SimpleAttributeSet set = new SimpleAttributeSet();
        Util.styleSheet().addCSSAttribute(set, CSS.Attribute.FONT_FAMILY,
                 mFontCombo.getSelectedItem().toString());
        set.addAttribute(HTML.Attribute.FACE, mFontCombo.getSelectedItem().toString());
        lwtext.richLabelBox.applyAttributes(set, false);
                
      lwtext.richLabelBox.select(0,0);
           
      lwtext.richLabelBox.setSize(lwtext.richLabelBox.getPreferredSize());                                        
               
          if (lwtext.getParent() !=null)
              lwtext.getParent().layout();
                 
                 
                
                 
       lwtext.notify(lwtext.richLabelBox, LWKey.Repaint); 
     }
   };
           
     private final PropertyChangeListener RichTextColorChangeListener =
new PropertyChangeListener() {
    public void propertyChange(PropertyChangeEvent e) {
        
        if (e instanceof LWPropertyChangeEvent == false)
            return;
                
        final RichTextBox activeRTB = (RichTextBox) VUE.getActive(RichTextBox.class);
                
                
        if (activeRTB == null && lwtext == null) {
            // no problem: just ignore if there's no active edit
            //tufts.Util.printStackTrace("FEP propertyChange: no active RichTextBox: " + e);
            return;
        }
                
        if (lwtext !=null)
           lwtext.richLabelBox.selectAll();
                
               
        final Color color = (Color) e.getNewValue();
        final SimpleAttributeSet set = new SimpleAttributeSet();
        final String colorString = "#" + Integer.toHexString(color.getRGB()).substring(2);
        toggleBulletsAction.setColor(colorString);
        toggleNumbersAction.setColor(colorString);
        Util.styleSheet().addCSSAttribute(set, CSS.Attribute.COLOR, colorString);
                
        set.addAttribute(HTML.Attribute.COLOR, colorString);
        if (activeRTB != null)
           activeRTB.applyAttributes(set, false);
        else
           lwtext.richLabelBox.applyAttributes(set, false);
                
        if (lwtext !=null)
        {
           lwtext.richLabelBox.select(0,0);
                    
           lwtext.richLabelBox.select(0,0);
          //lwtext.setLabel0(lwtext.richLabelBox.getRichText(), false);
          lwtext.richLabelBox.setSize(lwtext.richLabelBox.getPreferredSize());                                        
                   
              if (lwtext.getParent() !=null)
                  lwtext.getParent().layout();
                     
                     
                    
                     
           lwtext.notify(lwtext.richLabelBox, LWKey.Repaint); 
        }
    }
};
 ************/
// this called every time setText is called to ensure we get
// the font style encoded in our owning LWComponent
void copyStyle(LWComponent c) {
    if (DEBUG.TEXT)
        out("copyStyle " + c);

    //Basic Setup
    LWText srcText = (LWText) c;
    RichTextBox srcBox = srcText.getRichLabelBox();
    selectAll();
    SHTMLDocument srcDoc = (SHTMLDocument) srcBox.getDocument();
    SHTMLDocument doc = (SHTMLDocument) getDocument();
    SimpleAttributeSet set = new SimpleAttributeSet();
    SimpleAttributeSet alignSet = new SimpleAttributeSet();
    //Gather source information

    Element paragraphElement = srcDoc.getParagraphElement(1);

    if (paragraphElement.getName().equals("p-implied")) //we're in a list item
        paragraphElement = paragraphElement.getParentElement();

    AttributeSet paragraphAttributeSet = paragraphElement.getAttributes();

    Element charElem = srcDoc.getCharacterElement(1);
    AttributeSet charSet = charElem.getAttributes();
    Enumeration characterAttributeEnum = charSet.getAttributeNames();
    Enumeration elementEnum = paragraphAttributeSet.getAttributeNames();

    //Apply some attributes
    // System.out.println(paragraphElement.toString());
    while (elementEnum.hasMoreElements()) {
        Object o = elementEnum.nextElement();

        boolean isAlignSet = false;
        //System.out.println("P :: " +o.toString());
        if (o.toString().equals("text-align") && paragraphAttributeSet.getAttribute(o).toString().equals("left")
                && !isAlignSet) {
            //Left Align
            Util.styleSheet().addCSSAttribute(alignSet, CSS.Attribute.TEXT_ALIGN,
                    paragraphAttributeSet.getAttribute(o).toString());
            alignSet.addAttribute(HTML.Attribute.ALIGN, paragraphAttributeSet.getAttribute(o).toString());
        } else if (o.toString().equals("text-align")
                && paragraphAttributeSet.getAttribute(o).toString().equals("center") && !isAlignSet) {
            //Center Align
            Util.styleSheet().addCSSAttribute(alignSet, CSS.Attribute.TEXT_ALIGN,
                    paragraphAttributeSet.getAttribute(o).toString());
            alignSet.addAttribute(HTML.Attribute.ALIGN, paragraphAttributeSet.getAttribute(o).toString());
        } else if (o.toString().equals("text-align")
                && paragraphAttributeSet.getAttribute(o).toString().equals("right") && !isAlignSet) {
            //Right Align
            Util.styleSheet().addCSSAttribute(alignSet, CSS.Attribute.TEXT_ALIGN,
                    paragraphAttributeSet.getAttribute(o).toString());
            alignSet.addAttribute(HTML.Attribute.ALIGN, paragraphAttributeSet.getAttribute(o).toString());
        }

        if ((o.toString().equals("font-size")) || (o.toString().equals("size"))) {
            //Font Size
            Util.styleSheet().addCSSAttribute(set, CSS.Attribute.FONT_SIZE,
                    paragraphAttributeSet.getAttribute(o).toString());
            set.addAttribute(HTML.Attribute.SIZE, paragraphAttributeSet.getAttribute(o).toString());
        }

        else if ((o.toString().equals("font-family")) || (o.toString().equals("font-face"))
                || (o.toString().equals("face"))) {
            //Font Face
            Util.styleSheet().addCSSAttribute(set, CSS.Attribute.FONT_FAMILY,
                    paragraphAttributeSet.getAttribute(o).toString());
            set.addAttribute(HTML.Attribute.FACE, paragraphAttributeSet.getAttribute(o).toString());

        }
    }

    boolean isBold = false;
    boolean isItalic = false;
    boolean isUnderline = false;

    while (characterAttributeEnum.hasMoreElements()) {

        Object o = characterAttributeEnum.nextElement();
        //System.out.println("C :: " +o.toString() + "XXX " + charSet.getAttribute(o).toString());
        //System.out.println("Character element : " + o.toString() + " , " + charSet.getAttribute(o));
        if ((o.toString().equals("color"))) {
            //Color
            Util.styleSheet().addCSSAttribute(set, CSS.Attribute.COLOR, charSet.getAttribute(o).toString());
            set.addAttribute(HTML.Attribute.COLOR, charSet.getAttribute(o).toString());
        }

        if ((o.toString().equals("font-size")) || (o.toString().equals("size"))) {
            //Font Size
            Util.styleSheet().addCSSAttribute(set, CSS.Attribute.FONT_SIZE, charSet.getAttribute(o).toString());
            set.addAttribute(HTML.Attribute.SIZE, charSet.getAttribute(o).toString());
        }

        if ((o.toString().equals("font-family")) || (o.toString().equals("font-face"))
                || (o.toString().equals("face"))) {
            //Font Face
            Util.styleSheet().addCSSAttribute(set, CSS.Attribute.FONT_FAMILY,
                    charSet.getAttribute(o).toString());
            set.addAttribute(HTML.Attribute.FACE, charSet.getAttribute(o).toString());
        }

        if ((o.toString().equals("font-weight") && charSet.getAttribute(o).toString().equals("bold"))
                || o.toString().equals("b")) {
            Util.styleSheet().addCSSAttribute(set, CSS.Attribute.FONT_WEIGHT,
                    charSet.getAttribute(o).toString());
        }
        if ((o.toString().equals("font-style") && charSet.getAttribute(o).toString().equals("italic"))
                || o.toString().equals("i")) {
            Util.styleSheet().addCSSAttribute(set, CSS.Attribute.FONT_STYLE,
                    charSet.getAttribute(o).toString());
        }
        if ((o.toString().equals("text-decoration") && charSet.getAttribute(o).toString().equals("underline"))
                || o.toString().equals("u")) {
            Util.styleSheet().addCSSAttribute(set, CSS.Attribute.TEXT_DECORATION,
                    charSet.getAttribute(o).toString());
        }
    } //done looking at character attributes                                                

    applyAttributes(set, false);
    lwc.notify(this, LWKey.Repaint);
    applyAttributes(alignSet, true);
    lwc.notify(this, LWKey.Repaint);
    clearSelection();
    try {
        setSize(getPreferredSize());
    } catch (NullPointerException npe) {
    }
    /*      set = new SimpleAttributeSet();
          final String colorString = "#" + Integer.toHexString(color.getRGB()).substring(2);
          toggleBulletsAction.setColor(colorString);
          toggleNumbersAction.setColor(colorString);
          Util.styleSheet().addCSSAttribute(set, CSS.Attribute.COLOR, colorString);
                  
          set.addAttribute(HTML.Attribute.COLOR, colorString);
          if (activeRTB != null)
             activeRTB.applyAttributes(set, false);
          else
             lwtext.richLabelBox.applyAttributes(set, false);
                  
          if (lwtext !=null)
          {
             lwtext.richLabelBox.select(0,0);
            
             lwtext.richLabelBox.select(0,0);
            //lwtext.setLabel0(lwtext.richLabelBox.getRichText(), false);
            lwtext.richLabelBox.setSize(lwtext.richLabelBox.getPreferredSize());                                        
                     
      if (lwtext.getParent() !=null)
          lwtext.getParent().layout();
             
             
            
             
             lwtext.notify(lwtext.richLabelBox, LWKey.Repaint); 
          }*/
}