org.apache.batik.swing.svg
Class AbstractJSVGComponent

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by org.apache.batik.swing.gvt.AbstractJGVTComponent
                  extended by org.apache.batik.swing.gvt.JGVTComponent
                      extended by org.apache.batik.swing.svg.AbstractJSVGComponent
All Implemented Interfaces:
ImageObserver, MenuContainer, Serializable
Direct Known Subclasses:
JSVGComponent

public class AbstractJSVGComponent
extends JGVTComponent

This class represents a swing component that can display SVG documents. This component also lets you translate, zoom and rotate the document being displayed. This is the fundamental class for rendering SVG documents in a swing application. This class is made abstract so that concrete versions can be made for different JDK versions. In particular, this is for MouseWheelEvent support, which only exists in JDKs >= 1.4.

Rendering Process

The rendering process can be broken down into five phases. Not all of those steps are required - depending on the method used to specify the SVG document to display, but basically the steps in the rendering process are:

  1. Building a DOM tree
    If the loadSVGDocument(String) method is used, the SVG file is parsed and an SVG DOM Tree is built.
  2. Building a GVT tree
    Once an SVGDocument is created (using the step 1 or if the setSVGDocument(SVGDocument) method has been used) - a GVT tree is constructed. The GVT tree is the data structure used internally to render an SVG document. see the org.apache.batik.gvt package.
  3. Executing the SVGLoad event handlers
    If the document is dynamic, the scripts are initialized and the SVGLoad event is dispatched before the initial rendering.
  4. Rendering the GVT tree
    Then the GVT tree is rendered. see the org.apache.batik.gvt.renderer package.
  5. Running the document
    If the document is dynamic, the update threads are started.

Those steps are performed in a separate thread. To be notified to what happens and eventually perform some operations - such as resizing the window to the size of the document or get the SVGDocument built via a URI, five different listeners are provided (one per step): SVGDocumentLoaderListener, GVTTreeBuilderListener, SVGLoadEventDispatcherListener, GVTTreeRendererListener, UpdateManagerListener.

Each listener has methods to be notified of the start of a phase, and methods to be notified of the end of a phase. A phase cannot start before the preceding has finished.

The following example shows how you can get the size of an SVG document. Note that due to how SVG is designed (units, percentages...), the size of an SVG document can be known only once the SVGDocument has been analyzed (ie. the GVT tree has been constructed).

 final JSVGComponent svgComp = new JSVGComponent();
 svgComp.loadSVGDocument("foo.svg");
 svgComp.addGVTTreeBuilderListener(new GVTTreeBuilderAdapter() {
     public void gvtBuildCompleted(GVTTreeBuilderEvent evt) {
         Dimension2D size = svgComp.getSVGDocumentSize();
         // ...
     }
 });
 

The second example shows how you can access to the DOM tree when a URI has been used to display an SVG document.

 final JSVGComponent svgComp = new JSVGComponent();
 svgComp.loadSVGDocument("foo.svg");
 svgComp.addSVGDocumentLoaderListener(new SVGDocumentLoaderAdapter() {
     public void documentLoadingCompleted(SVGDocumentLoaderEvent evt) {
         SVGDocument svgDoc = svgComp.getSVGDocument();
         //...
     }
 });
 

Conformed to the single thread rule of swing, the listeners are executed in the swing thread. The sequence of the method calls for a particular listener and the order of the listeners themselves are guaranteed.

User Agent

The JSVGComponent can pick up some informations to a user agent. The SVGUserAgent provides a way to control the resolution used to display an SVG document (controling the pixel to millimeter conversion factor), perform an operation in respond to a click on an hyperlink, control the default language to use, or specify a user stylesheet, or how to display errors when an error occured while building/rendering a document (invalid XML file, missing attributes...).

See Also:
Serialized Form

Nested Class Summary
protected  class AbstractJSVGComponent.BridgeUserAgent
          To hide the user-agent methods.
protected static class AbstractJSVGComponent.BridgeUserAgentWrapper
          The user-agent wrapper, which call the methods in the event thread.
protected  class AbstractJSVGComponent.JSVGComponentListener
           
protected  class AbstractJSVGComponent.SVGListener
          To hide the listener methods.
 
Nested classes/interfaces inherited from class org.apache.batik.swing.gvt.JGVTComponent
JGVTComponent.ExtendedListener
 
Nested classes/interfaces inherited from class org.apache.batik.swing.gvt.AbstractJGVTComponent
AbstractJGVTComponent.Listener, AbstractJGVTComponent.UnixTextSelectionListener
 
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
 
Field Summary
protected  Runnable afterStopRunnable
           
static int ALWAYS_DYNAMIC
          Means that all document must be considered as dynamic.
static int ALWAYS_INTERACTIVE
          Means that all document must be considered as interactive.
static int ALWAYS_STATIC
          Means that all document must be considered as static.
protected  float animationLimitingAmount
          The amount of animation limiting.
protected  int animationLimitingMode
          The animation limiting mode.
static int AUTODETECT
          Means that the component must auto detect whether the current document is static or dynamic.
protected  BridgeContext bridgeContext
          The current bridge context.
static String BROKEN_LINK_TITLE
          String constant for the resource with the text for the title of the info tooltip for brokin link images.
protected  SVGDocumentLoader documentLoader
          The document loader.
protected  int documentState
          The document state.
protected static Set FEATURES
           
protected  String fragmentIdentifier
          The current document fragment identifier.
protected  GVTTreeBuilder gvtTreeBuilder
          The GVT tree builder.
protected  List gvtTreeBuilderListeners
          The GVT tree builder listeners.
protected  boolean isDynamicDocument
          Whether the current document has dynamic features.
protected  boolean isInteractiveDocument
          Whether the current document has dynamic features.
protected  AbstractJSVGComponent.JSVGComponentListener jsvgComponentListener
          The JGVTComponentListener.
protected  List linkActivationListeners
          The link activation listeners.
protected  DocumentLoader loader
          The concrete bridge document loader.
protected  SVGDocumentLoader nextDocumentLoader
          The next document loader to run.
protected  GVTTreeBuilder nextGVTTreeBuilder
          The next GVT tree builder to run.
protected  UpdateManager nextUpdateManager
          The next update manager.
protected  Dimension prevComponentSize
           
protected  boolean recenterOnResize
           
static String SCRIPT_ALERT
          String constant for the resource with the text for a script alert dialog.
static String SCRIPT_CONFIRM
          String constant for the resource with the text for a script confim dialog.
static String SCRIPT_PROMPT
          String constant for the resource with the text for a script prompt dialog.
protected  boolean selfCallingDisableInteractions
          Set to true before component calls setDisableInteractors so it knows that the users isn't the one calling it.
protected  org.w3c.dom.svg.SVGDocument svgDocument
          The current SVG document.
protected  List svgDocumentLoaderListeners
          The document loader listeners.
protected  SVGLoadEventDispatcher svgLoadEventDispatcher
          The SVGLoadEventDispatcher.
protected  List svgLoadEventDispatcherListeners
          The SVG onload dispatcher listeners.
protected  SVGUserAgent svgUserAgent
          The SVG user agent.
protected  UpdateManager updateManager
          The update manager.
protected  List updateManagerListeners
          The update manager listeners.
protected  SVGUpdateOverlay updateOverlay
           
protected  UserAgent userAgent
          The user agent.
protected  boolean userSetDisableInteractions
          Set to true if the user ever calls setDisableInteractions
protected  AffineTransform viewingTransform
           
 
Fields inherited from class org.apache.batik.swing.gvt.AbstractJGVTComponent
disableInteractions, doubleBufferedRendering, eventDispatcher, eventsEnabled, gvtRoot, gvtTreeRenderer, gvtTreeRendererListeners, image, initialTransform, interactor, interactors, jgvtListeners, listener, needRender, overlays, paintingTransform, progressivePaint, progressivePaintThread, renderer, rendererFactory, renderingTransform, selectableText, suspendInteractions, textSelectionManager, useUnixTextSelection
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, 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
 
Constructor Summary
AbstractJSVGComponent()
          Creates a new AbstractJSVGComponent.
AbstractJSVGComponent(SVGUserAgent ua, boolean eventsEnabled, boolean selectableText)
          Creates a new AbstractJSVGComponent.
 
Method Summary
 void addGVTTreeBuilderListener(GVTTreeBuilderListener l)
          Adds a GVTTreeBuilderListener to this component.
 void addLinkActivationListener(LinkActivationListener l)
          Adds a LinkActivationListener to this component.
 void addSVGDocumentLoaderListener(SVGDocumentLoaderListener l)
          Adds a SVGDocumentLoaderListener to this component.
 void addSVGLoadEventDispatcherListener(SVGLoadEventDispatcherListener l)
          Adds a SVGLoadEventDispatcherListener to this component.
 void addUpdateManagerListener(UpdateManagerListener l)
          Adds a UpdateManagerListener to this component.
protected  AffineTransform calculateViewingTransform(String fragIdent, org.w3c.dom.svg.SVGSVGElement svgElt)
           
 void clearUserSetDisableInteractions()
          Clears the boolean that indicates the 'user' has set disable interactions so that the canvas uses the value from documents.
protected  boolean computeRenderingTransform()
          Computes the transform used for rendering.
protected  BridgeContext createBridgeContext(SVGOMDocument doc)
          Creates a new bridge context.
protected  ImageRenderer createImageRenderer()
          Creates a new renderer.
protected  AbstractJGVTComponent.Listener createListener()
          Creates an instance of Listener.
protected  UserAgent createUserAgent()
          Creates a UserAgent.
 void dispose()
           
 void flushImageCache()
          Removes all images from the image cache.
 CanvasGraphicsNode getCanvasGraphicsNode()
           
protected  CanvasGraphicsNode getCanvasGraphicsNode(GraphicsNode gn)
           
 String getFragmentIdentifier()
          Returns the current's document fragment identifier.
 boolean getRecenterOnResize()
          Indicates if the canvas should recenter the content after the canvas is resized.
 org.w3c.dom.svg.SVGDocument getSVGDocument()
          Returns the current SVG document.
 Dimension2D getSVGDocumentSize()
          Returns the size of the SVG document.
 UpdateManager getUpdateManager()
          Returns the current update manager.
 AffineTransform getViewBoxTransform()
          Returns the transform from viewBox coords to screen coords
 AffineTransform getViewingTransform()
           
protected  void handleException(Exception e)
          Handles an exception.
protected  void installSVGDocument(org.w3c.dom.svg.SVGDocument doc)
          This does the real work of installing the SVG Document after the update manager from the previous document (if any) has been properly 'shut down'.
 boolean isDynamic()
          Tells whether the component use dynamic features to process the current document.
 boolean isInteractive()
          Tells whether the component use dynamic features to process the current document.
 void loadSVGDocument(String url)
          Loads a SVG document from the given URL.
 void removeGVTTreeBuilderListener(GVTTreeBuilderListener l)
          Removes a GVTTreeBuilderListener from this component.
 void removeLinkActivationListener(LinkActivationListener l)
          Removes a LinkActivationListener from this component.
 void removeSVGDocumentLoaderListener(SVGDocumentLoaderListener l)
          Removes a SVGDocumentLoaderListener from this component.
 void removeSVGLoadEventDispatcherListener(SVGLoadEventDispatcherListener l)
          Removes a SVGLoadEventDispatcherListener from this component.
 void removeUpdateManagerListener(UpdateManagerListener l)
          Removes a UpdateManagerListener from this component.
protected  void renderGVTTree()
          Renders the GVT tree.
 void resumeProcessing()
          Resumes the processing of the current document.
 void setAnimationLimitingCPU(float pc)
          Sets the animation limiting mode to a percentage of CPU.
 void setAnimationLimitingFPS(float fps)
          Sets the animation limiting mode to a number of frames per second.
 void setAnimationLimitingNone()
          Sets the animation limiting mode to "none".
protected  void setBridgeContextAnimationLimitingMode()
          Sets the animation limiting mode on the current bridge context.
 void setDisableInteractions(boolean b)
          Turn off all 'interactor' objects (pan, zoom, etc) if 'b' is true, turn them on if 'b' is false.
 void setDocument(Document doc)
          Sets the Document to display.
 void setDocumentState(int state)
          Sets the document state.
 void setFragmentIdentifier(String fi)
          Sets the current fragment identifier.
 void setGraphicsNode(GraphicsNode gn, boolean createDispatcher)
          Sets the GVT tree to display.
 void setMySize(Dimension d)
          This method is called when the component knows the desired size of the window (based on width/height of outermost SVG element).
 void setRecenterOnResize(boolean recenterOnResize)
          Returns sate of the recenter on resize flag.
 void setSVGDocument(org.w3c.dom.svg.SVGDocument doc)
          Sets the SVGDocument to display.
 void showAlert(String message)
          Shows an alert dialog box.
 boolean showConfirm(String message)
          Shows a confirm dialog box.
 String showPrompt(String message)
          Shows a prompt dialog box.
 String showPrompt(String message, String defaultValue)
          Shows a prompt dialog box.
protected  void startGVTTreeBuilder()
          Starts a tree builder.
protected  void startSVGLoadEventDispatcher(GraphicsNode root)
          Starts a SVGLoadEventDispatcher thread.
 void stopProcessing()
          Stops the processing of the current document.
protected  void stopThenRun(Runnable r)
          This method calls stop processing waits for all threads to die then runs the Runnable in the event queue thread.
 void suspendProcessing()
          Suspend the processing of the current document.
protected  boolean updateRenderingTransform()
          Updates the value of the transform used for rendering.
 void updateZoomAndPanEnable(Document doc)
          Enables/Disables Zoom And Pan based on the zoom and pan attribute of the currently installed document, Unless the user has set the Interactions State.
 
Methods inherited from class org.apache.batik.swing.gvt.JGVTComponent
addAWTListeners
 
Methods inherited from class org.apache.batik.swing.gvt.AbstractJGVTComponent
addGVTTreeRendererListener, addJGVTComponentListener, createTextSelectionManager, deselectAll, flush, flush, getDisableInteractions, getDoubleBufferedRendering, getGraphicsNode, getInitialTransform, getInteractors, getOffScreen, getOverlays, getPaintingTransform, getProgressivePaint, getRenderingTransform, getRenderRect, getSelectionOverlayColor, getSelectionOverlayStrokeColor, getTextSelectionManager, getUseUnixTextSelection, immediateRepaint, initializeEventHandling, isSelectionOverlayXORMode, paintComponent, releaseRenderingReferences, removeGVTTreeRendererListener, removeJGVTComponentListener, resetRenderingTransform, scheduleGVTRendering, select, setDoubleBufferedRendering, setGraphicsNode, setPaintingTransform, setProgressivePaint, setRenderingTransform, setRenderingTransform, setSelectionOverlayColor, setSelectionOverlayStrokeColor, setSelectionOverlayXORMode, setUseUnixTextSelection
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, 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, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, 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, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, 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, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange,