Class XHTMLPanel

  • All Implemented Interfaces:
    java.awt.event.ComponentListener, java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener, javax.accessibility.Accessible, UserInterface, FormSubmissionListener
    Direct Known Subclasses:
    ScalableXHTMLPanel

    public class XHTMLPanel
    extends BasicPanel

    XHTMLPanel is a simple Swing component that renders valid XHTML content in a Java program. It is scrolling aware so you can safely drop it into a JScrollPane. The most common usage is to stuff a URL into it and then add it to your JFrame. Ex:

     import org.xhtmlrenderer.simple.*;
     .....
     

    public static void main(String[] args) {

    // set up the xhtml panel XHTMLPanel xhtml = new XHTMLPanel(); xhtml.setDocument(new URL("http://myserver.com/page.xhtml"));

    JScrollPane scroll = new JScrollPane(xhtml); JFrame frame = new JFrame("Demo"); frame.getContentPane().add(scroll); frame.pack(); frame.setSize(500,600); frame.show(); }

    XHTMLPanel renders XHTML and XML which can be loaded as valid Document instances. You should make sure the document you want to render is well-formed. For XHTML, there is always a default stylesheet available, even if no CSS is attached to the XHTML you are loading. For XML, there is no default stylesheet, so you should have one attached to your XML before trying to render it using the xml-stylesheer processing instruction. XHTMLPanel has methods to load documents from a uri (setDocument(String uri)), from a Document instance (setDocument(Document)) or from an InputStream (BasicPanel.setDocument(java.io.InputStream,String)).

    XHTMLPanel also lets you make simple changes with simple methods like setFontScalingFactor(float). If you want to make other changes you will need to get the rendering context (BasicPanel.getSharedContext()) and call methods on that. Ex:

     XHTMLPanel xhtml = new XHTMLPanel();
     RenderingContext ctx = xhtml.getRenderingContext();
     ctx.setLogging(true); // turn on logging
     ctx.setValidating(true); // turn on doctype validation
     ctx.addFont(fnt,"Arial"); // redefine a font
     ctx.setDomImplementation("com.cooldom.DomImpl");
     

    XHTMLPanel comes with a pre-installed MouseListener which handles :hover events used for rollovers ( @see org.xhtmlrenderer.swing.HoverListener ). XHTMLPanel also comes with a pre-installed LinkListener used to follow links. ( @see org.xhtmlrenderer.swing.LinkListener ) If you want to disable these for some reason you can get the list of mouse listeners and remove them all.

    Author:
    Joshua Marinacci (joshy@joshy.net)
    See Also:
    The Flying Saucer Home Page, RenderingContext, Serialized Form
    • Nested Class Summary

      • Nested classes/interfaces inherited from class javax.swing.JComponent

        javax.swing.JComponent.AccessibleJComponent
      • Nested classes/interfaces inherited from class java.awt.Component

        java.awt.Component.BaselineResizeBehavior
    • Field Summary

      • Fields inherited from class javax.swing.JComponent

        TOOL_TIP_TEXT_KEY, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
      • Fields inherited from class java.awt.Component

        BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
      • Fields inherited from interface java.awt.image.ImageObserver

        ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void decrementFontSize()
      Decrements all rendered fonts on the current document by the current scaling factor for the panel.
      float getMaxFontScale()
      Returns the maximum font scaling that may be applied, e.g.
      float getMinFontScale()
      Returns the minimum font scaling that may be applied, e.g.
      void incrementFontSize()
      Increments all rendered fonts on the current document by the current scaling factor for the panel.
      void relayout()
      Lays out the current document again, and re-renders.
      void resetFontSize()
      Resets all rendered fonts on the current document to the font size specified in the document's styling instructions.
      void setDocument​(java.io.File file)
      Renders a Document read from an InputStream using a URL as a base URL for relative paths.
      void setDocument​(java.io.InputStream stream, java.lang.String url)
      Renders a Document read from an InputStream using a URL as a base URL for relative paths.
      void setDocument​(java.lang.String uri)
      Loads and renders a Document given a uri.
      void setDocument​(org.w3c.dom.Document doc)
      Renders an XML Document instance.
      void setDocument​(org.w3c.dom.Document doc, java.lang.String url)
      Renders a Document using a URL as a base URL for relative paths.
      void setFontScalingFactor​(float scaling)
      Sets the scaling factor used by incrementFontSize() and decrementFontSize()--both scale the font up or down by this scaling factor.
      void setMaxFontScale​(float f)
      Sets the maximum font scaling that may be applied, e.g.
      void setMinFontScale​(float f)
      Sets the minimum font scaling that may be applied, e.g.
      void setSharedContext​(SharedContext ctx)
      Sets the RenderingContext attribute of the XHTMLPanel object.
      • Methods inherited from class javax.swing.JPanel

        getAccessibleContext, getUI, getUIClassID, setUI, updateUI
      • Methods inherited from class javax.swing.JComponent

        addAncestorListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintImmediately, paintImmediately, print, printAll, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
      • Methods inherited from class java.awt.Container

        add, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, transferFocusDownCycle, validate
      • Methods inherited from class java.awt.Component

        action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, contains, createImage, createImage, createVolatileImage, createVolatileImage, dispatchEvent, enable, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
      • Methods inherited from class java.lang.Object

        equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • Constructor Detail

      • XHTMLPanel

        public XHTMLPanel()
        Instantiates an XHTMLPanel with no Document loaded by default.
      • XHTMLPanel

        public XHTMLPanel​(UserAgentCallback uac)
        Instantiates a panel with a custom UserAgentCallback implementation.
        Parameters:
        uac - The custom UserAgentCallback implementation.
    • Method Detail

      • relayout

        public void relayout()
        Lays out the current document again, and re-renders.
      • setDocument

        public void setDocument​(java.lang.String uri)
        Loads and renders a Document given a uri. The uri is resolved by the UserAgentCallback
        Overrides:
        setDocument in class BasicPanel
        Parameters:
        uri -
      • setDocument

        public void setDocument​(org.w3c.dom.Document doc)
        Renders an XML Document instance. Make sure that no relative resources are needed
        Parameters:
        doc - The document to render.
      • setDocument

        public void setDocument​(org.w3c.dom.Document doc,
                                java.lang.String url)
        Renders a Document using a URL as a base URL for relative paths.
        Overrides:
        setDocument in class BasicPanel
        Parameters:
        doc - The new document value
        url - The new document value
      • setDocument

        public void setDocument​(java.io.InputStream stream,
                                java.lang.String url)
                         throws java.lang.Exception
        Renders a Document read from an InputStream using a URL as a base URL for relative paths.
        Parameters:
        stream - The stream to read the Document from.
        url - The URL used to resolve relative path references.
        Throws:
        java.lang.Exception
      • setDocument

        public void setDocument​(java.io.File file)
                         throws java.lang.Exception
        Renders a Document read from an InputStream using a URL as a base URL for relative paths.
        Parameters:
        file - The file to read the Document from. Relative paths will be resolved based on the file's parent directory.
        Throws:
        java.lang.Exception
      • setSharedContext

        public void setSharedContext​(SharedContext ctx)
        Sets the RenderingContext attribute of the XHTMLPanel object. Generally you should not use this unless you have a heavily customized context to use. To modify just some rendering behavior, consider using BasicPanel.getSharedContext() to retrieve the current context, and using mutators to change its behavior.
        Overrides:
        setSharedContext in class BasicPanel
        Parameters:
        ctx - A new RenderingContext to use for rendering.
      • setFontScalingFactor

        public void setFontScalingFactor​(float scaling)
        Sets the scaling factor used by incrementFontSize() and decrementFontSize()--both scale the font up or down by this scaling factor. The scaling roughly modifies the font size as a multiplier or divisor. A scaling factor of 1.2 applied against a font size of 10pt results in a scaled font of 12pt. The default scaling factor is 1.2F.
      • incrementFontSize

        public void incrementFontSize()
        Increments all rendered fonts on the current document by the current scaling factor for the panel. Scaling applies culmulatively, which means that multiple calls to this method scale fonts larger and larger by applying the current scaling factor against itself. You can modify the scaling factor by setFontScalingFactor(float), and reset to the document's specified font size with resetFontSize().
      • resetFontSize

        public void resetFontSize()
        Resets all rendered fonts on the current document to the font size specified in the document's styling instructions.
      • decrementFontSize

        public void decrementFontSize()
        Decrements all rendered fonts on the current document by the current scaling factor for the panel. Scaling applies culmulatively, which means that multiple calls to this method scale fonts smaller and smaller by applying the current scaling factor against itself. You can modify the scaling factor by setFontScalingFactor(float), and reset to the document's specified font size with resetFontSize().
      • getMaxFontScale

        public float getMaxFontScale()
        Returns the maximum font scaling that may be applied, e.g. 3 times assigned font size.
      • getMinFontScale

        public float getMinFontScale()
        Returns the minimum font scaling that may be applied, e.g. 0.5 times assigned font size.
      • setMaxFontScale

        public void setMaxFontScale​(float f)
        Sets the maximum font scaling that may be applied, e.g. 3 times assigned font size. Calling incrementFontSize() after this scale has been reached doesn't have an effect.
      • setMinFontScale

        public void setMinFontScale​(float f)
        Sets the minimum font scaling that may be applied, e.g. 3 times assigned font size. Calling decrementFontSize() after this scale has been reached doesn't have an effect.