⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 basichtml.java

📁 java jdk 1.4的源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * @(#)BasicHTML.java	1.17 03/01/23 * * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */package javax.swing.plaf.basic;import java.io.*;import java.awt.*;import java.net.URL;import javax.swing.*;import javax.swing.text.*;import javax.swing.text.html.*;/** * Support for providing html views for the swing components. * This translates a simple html string to a javax.swing.text.View * implementation that can render the html and provide the necessary * layout semantics. * * @author  Timothy Prinzing * @version 1.17 01/23/03 */public class BasicHTML {    /**     * Create an html renderer for the given component and     * string of html.     */    public static View createHTMLView(JComponent c, String html) {	BasicEditorKit kit = getFactory();	Document doc = kit.createDefaultDocument(c.getFont(),                                                 c.getForeground());	Object base = c.getClientProperty(documentBaseKey);	if (base instanceof URL) {	    ((HTMLDocument)doc).setBase((URL)base);	}	Reader r = new StringReader(html);	try {	    kit.read(r, doc, 0);	} catch (Throwable e) {	}	ViewFactory f = kit.getViewFactory();	View hview = f.create(doc.getDefaultRootElement());	View v = new Renderer(c, f, hview);	return v;    }    /**     * Check the given string to see if it should trigger the     * html rendering logic in a non-text component that supports      * html rendering.     */    public static boolean isHTMLString(String s) {	if (s != null) {	    if ((s.length() >= 6) && (s.charAt(0) == '<') && (s.charAt(5) == '>')) {		String tag = s.substring(1,5);		return tag.equalsIgnoreCase(propertyKey);	    }	}	return false;    }    /**     * Stash the HTML render for the given text into the client     * properties of the given JComponent. If the given text is      * <em>NOT HTML</em> the property will be cleared of any     * renderer.     * <p>     * This method is useful for ComponentUI implementations     * that are static (i.e. shared) and get their state     * entirely from the JComponent.     */    public static void updateRenderer(JComponent c, String text) {	View value = null;	String key = null;	if (BasicHTML.isHTMLString(text)) {	    value = BasicHTML.createHTMLView(c, text);	}	c.putClientProperty(BasicHTML.propertyKey, value);    }    /**     * Key to use for the html renderer when stored as a      * client property of a JComponent.     */    public static final String propertyKey = "html";    /**     * Key stored as a client property to indicate the base that relative     * references are resolved against. For example, lets say you keep     * your images in the directory resources relative to the code path,     * you would use the following the set the base:     * <pre>     *   jComponent.putClientProperty(documentBaseKey,     *                                xxx.class.getResource("resources/"));     * </pre>     */    public static final String documentBaseKey = "html.base";    static BasicEditorKit getFactory() {	if (basicHTMLFactory == null) {            basicHTMLViewFactory = new BasicHTMLViewFactory();	    basicHTMLFactory = new BasicEditorKit();	}	return basicHTMLFactory;    }    /**     * The source of the html renderers     */    private static BasicEditorKit basicHTMLFactory;    /**     * Creates the Views that visually represent the model.     */    private static ViewFactory basicHTMLViewFactory;    /**     * Overrides to the default stylesheet.  Should consider     * just creating a completely fresh stylesheet.     */    private static final String styleChanges =     "p { margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0 }" +    "body { margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0 }";    /**     * The views produced for the ComponentUI implementations aren't     * going to be edited and don't need full html support.  This kit     * alters the HTMLEditorKit to try and trim things down a bit.       * It does the following:     * <ul>     * <li>It doesn't produce Views for things like comments,      * head, title, unknown tags, etc.       * <li>It installs a different set of css settings from the default     * provided by HTMLEditorKit.     * </ul>     */    static class BasicEditorKit extends HTMLEditorKit {	/** Shared base style for all documents created by us use. */	private static StyleSheet defaultStyles;	/**	 * Overriden to return our own slimmed down style sheet.	 */	public StyleSheet getStyleSheet() {	    if (defaultStyles == null) {		defaultStyles = new StyleSheet();		StringReader r = new StringReader(styleChanges);		try {		    defaultStyles.loadRules(r, null);		} catch (Throwable e) {		    // don't want to die in static initialization... 		    // just display things wrong.		}		r.close();		defaultStyles.addStyleSheet(super.getStyleSheet());	    }	    return defaultStyles;	}	/**	 * Sets the async policy to flush everything in one chunk, and	 * to not display unknown tags.	 */        public Document createDefaultDocument(Font defaultFont,                                              Color foreground) {	    StyleSheet styles = getStyleSheet();	    StyleSheet ss = new StyleSheet();	    ss.addStyleSheet(styles);	    BasicDocument doc = new BasicDocument(ss, defaultFont, foreground);	    doc.setAsynchronousLoadPriority(Integer.MAX_VALUE);	    doc.setPreservesUnknownTags(false);	    return doc;	}        /**         * Returns the ViewFactory that is used to make sure the Views don't         * load in the background.         */        public ViewFactory getViewFactory() {            return basicHTMLViewFactory;        }    }    /**     * BasicHTMLViewFactory extends HTMLFactory to force images to be loaded     * synchronously.     */    static class BasicHTMLViewFactory extends HTMLEditorKit.HTMLFactory {        public View create(Element elem) {            View view = super.create(elem);            if (view instanceof ImageView) {                ((ImageView)view).setLoadsSynchronously(true);            }            return view;        }    }    /**     * The subclass of HTMLDocument that is used as the model. getForeground     * is overridden to return the foreground property from the Component this     * was created for.     */    static class BasicDocument extends HTMLDocument {	/** The host, that is where we are rendering. */	// private JComponent host;	BasicDocument(StyleSheet s, Font defaultFont, Color foreground) {	    super(s);	    setPreservesUnknownTags(false);            setFontAndColor(defaultFont, foreground);	}        /**         * Sets the default font and default color. These are set by         * adding a rule for the body that specifies the font and color.         * This allows the html to override these should it wish to have         * a custom font or color.         */	private void setFontAndColor(Font font, Color fg) {            StringBuffer rule = null;            if (font != null) {                rule = new StringBuffer("body { font-family: ");                rule.append(font.getFamily());                rule.append(";");                rule.append(" font-size: ");                rule.append(font.getSize());                rule.append("pt");                if (font.isBold()) {                    rule.append("; font-weight: 700");                }                if (font.isItalic()) {                    rule.append("; font-style: italic");                }            }            if (fg != null) {                if (rule == null) {                    rule = new StringBuffer("body { color: #");                }                else {                    rule.append("; color: #");                }                if (fg.getRed() < 16) {                    rule.append('0');                }                rule.append(Integer.toHexString(fg.getRed()));                if (fg.getGreen() < 16) {                    rule.append('0');                }                rule.append(Integer.toHexString(fg.getGreen()));                if (fg.getBlue() < 16) {                    rule.append('0');                }                rule.append(Integer.toHexString(fg.getBlue()));            }            if (rule != null) {                rule.append(" }");                try {                    getStyleSheet().addRule(rule.toString());                } catch (RuntimeException re) {}            }	}    }    /**     * Root text view that acts as an HTML renderer.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -