Class SvgIcon

java.lang.Object
javax.swing.ImageIcon
swingtree.style.SvgIcon
All Implemented Interfaces:
Serializable, Accessible, Icon

public final class SvgIcon extends ImageIcon
A specialized ImageIcon subclass that allows you to use SVG based icon images in your GUI. This in essence just a wrapper around the JSVG library, which renders SVG images using the Java2D graphics API.

You may use this like a regular ImageIcon, but have to keep in mind that SVG documents do not really have a fixed size, meaning that the getIconWidth() and getIconHeight() on a freshly loaded SvgIcon will return -1 which causes the icon to be rendered according to the width and height of the component it is rendered into (see paintIcon(Component, java.awt.Graphics, int, int)).

If you want to render the icon with a fixed size, you can use the withIconWidth(int) and withIconHeight(int) or withIconSize(int, int) methods to create a new SvgIcon with the given width and height.

An SvgIcon with an undefined width or height will also be using the UI.FitComponent and UI.Placement policies to determine how the icon should be placed and sized within a component. Use the withFitComponent(UI.FitComponent) and withPreferredPlacement(UI.Placement) methods to create a new SvgIcon with the given policies and use the getFitComponent() and getPreferredPlacement() methods to retrieve the current policies (Not that these will not have any effect if the width and height are both defined).

Also note that the direct use of this class and it's API is discouraged in favour of simply calling the UIFactoryMethods.findIcon(String) or UIFactoryMethods.findSvgIcon(String) methods, which will automatically load and cache all the icons for you.

See Also:
  • Method Details

    • at

      public static SvgIcon at(String path)
      Tries to create an SvgIcon from a resource path defined by the supplied string.
      Parameters:
      path - The path to the SVG document.
      Returns:
      A new SvgIcon created from the SVG found at the given path.
    • at

      public static SvgIcon at(String path, Size size)
      Creates an SvgIcon from a resource path and a custom size.
      Parameters:
      path - The path to the SVG document.
      size - The size of the icon in the form of a Size.
      Returns:
      A new SvgIcon created from the SVG found at the given path and with the given size.
    • at

      public static SvgIcon at(URL svgUrl)
      Creates an SvgIcon from the supplied URL pointing to an SVG document. If parsing the SVG document fails, an empty icon will be created, which does not render anything. The resulting icon will have an unknown size, placement and fit policy, meaning that it will be rendered according to the size of the component it is rendered into (see paintIcon(Component, Graphics, int, int)).
      Parameters:
      svgUrl - The URL to the SVG document.
      Returns:
      A new SvgIcon created from the SVG found at the supplied URL.
    • at

      public static SvgIcon at(URL svgUrl, Size size)
      Parameters:
      svgUrl - The URL to the SVG document.
      size - The size of the icon in the form of a Size.
      Returns:
      A new SvgIcon created from the SVG found at the supplied URL and with the given size.
    • of

      public static SvgIcon of(String svgString)
      Allows you to directly create an SvgIcon from a string containing an SVG text.
      Parameters:
      svgString - A string containing SVG text.
      Returns:
      A new SvgIcon created from a String containing an SVG document.
    • of

      public static SvgIcon of(String svgString, Size size)
      Allows you to directly create an SvgIcon from a string containing an SVG text, with a custom width and height defined by the supplied Size.
      Parameters:
      svgString - A string containing SVG text.
      size - A Size object containing the desired SVG width and height.
      Returns:
      A new SvgIcon created from a String containing an SVG document and a custom width and height...
    • of

      public static SvgIcon of(InputStream stream)
      Reads the SVG document from the supplied input stream and creates an SvgIcon from it. If parsing the SVG document fails, an empty icon will be created, which does not render anything. The resulting icon will have an unknown size, placement and fit policy, meaning that it will be rendered according to the size of the component it is rendered into (see paintIcon(Component, Graphics, int, int)). If you want to customize the size, layout and placement of the icon, consider creating derived versions using the withIconWidth(int), withIconHeight(int), withIconSize(int, int), withFitComponent(UI.FitComponent) and withPreferredPlacement(UI.Placement) methods.
      Parameters:
      stream - The input stream supplying the text data of the SVG document.
    • of

      public static SvgIcon of(InputStream stream, Size size)
      Reads the SVG document from the supplied input stream and creates an SvgIcon from it with a custom width and height defined by the supplied Size.
      If parsing the SVG document fails, an empty icon will be created, which does not render anything. The resulting icon will have the given size, but the default placement and fit policy, meaning that it will be rendered according to the size of the component it is rendered into (see paintIcon(Component, Graphics, int, int)).
      If you want to customize the layout and placement of the icon, consider creating derived versions using the withFitComponent(UI.FitComponent) and withPreferredPlacement(UI.Placement) methods.
      Parameters:
      stream - The input stream supplying the text data of the SVG document.
      size - The size of the icon in the form of a Size.
    • of

      public static SvgIcon of(com.github.weisj.jsvg.SVGDocument svgDocument)
      Allows you to create an SvgIcon from an already loaded SVGDocument. The icon will be created with an unknown size, meaning that it will be rendered according to the size of the component it is rendered into (see paintIcon(Component, Graphics, int, int)). If you want to customize the size, layout and placement of the icon, consider creating derived versions using the withIconWidth(int), withIconHeight(int), withIconSize(int, int), withFitComponent(UI.FitComponent) and withPreferredPlacement(UI.Placement) methods.
      Parameters:
      svgDocument - The already loaded SVG document, which will be used to render the icon.
    • of

      public static SvgIcon of(com.github.weisj.jsvg.SVGDocument svgDocument, Size size)
      Allows you to create an SvgIcon from an already loaded SVGDocument with a custom width and height defined by the supplied Size.
      If you want to customize the layout and placement of the icon, consider creating derived versions using the withFitComponent(UI.FitComponent) and withPreferredPlacement(UI.Placement) methods.
      Parameters:
      svgDocument - The already loaded SVG document, which will be used to render the icon.
      size - The size of the icon in the form of a Size.
    • widthUnitString

      public String widthUnitString()
      Returns the unit of the width of the icon or an empty String if the encountered unit is unknown. If the underlying document reports a valid width without a unit postfix, then it will be interpreted as "px"!
      Please note that this method does not return the exact same unit found in the underlying document, since not all units are supported by the SwingTree icon...
      Returns:
      The unit of the width of the SVG icon in the form of a string similar to how it is present in the underlying document.
    • heightUnitString

      public String heightUnitString()
      Returns the unit of the height of the icon or an empty String if the encountered unit is unknown. If the underlying document reports a valid height without a unit postfix, then it will be interpreted as "px"!
      Please note that this method does not return the exact same unit found in the underlying document, since not all units are supported by the SwingTree icon...
      Returns:
      The unit of the height of the SVG icon in the form of a string similar to how it is present in the underlying document.
    • getIconWidth

      public int getIconWidth()
      Exposes the width of the icon in component pixel space, or -1 if the icon should be rendered according to the width of a given component or the width of the SVG document itself. (...or other policies such as UI.FitComponent and UI.Placement).
      Note that the returned width is dynamically scaled according to the current UI.scale() value. This is to ensure that the icon is rendered at the correct size according to the current DPI settings. If you want the unscaled width, use getBaseWidth().
      Specified by:
      getIconWidth in interface Icon
      Overrides:
      getIconWidth in class ImageIcon
      Returns:
      The width of the icon in component pixel space, or -1 if the icon should be rendered according to the width of a given component or the width of the SVG document itself.
      See Also:
    • withIconWidth

      public SvgIcon withIconWidth(int newWidth)
      Creates an updated SvgIcon with a new width measured in "developer pixel", which effectively translates to what is being reported by getBaseWidth(), and indirectly also getIconWidth() (which is scaled to component pixel space). Since the supplied width is developer pixel based, the existing width-unit in this instance will be overridden to being pixel based in the returned instance

      This method is useful when you want to adjust the width of an SVG without affecting the (pixel based) height!
      For example, calling icon.withIconWidth(100) on an icon with dimensions 20pxx20px will result in an icon that is 100px×20px pixels in size.
      So be aware that using this method may also change the aspect ratio of the icon, possibly causing it to be rendered distorted...


      However, in case of the height of this icon being percentage based, then the new icon will have its height overridden to -1 and the unit of the height will also always be pixel based (see widthUnitString() and heightUnitString()).

      Parameters:
      newWidth - The width of the icon, or -1 if the icon should be rendered according to the width of a given component or the width of the SVG document itself.
      Returns:
      A new SvgIcon with the given width. If the width is -1, the icon will be rendered according to the width of a given component or the width of the SVG document itself.
      See Also:
    • getIconHeight

      public int getIconHeight()
      Exposes the height of the icon in component pixel space, or -1 if the icon should be rendered according to the height of a given component or the height of the SVG document itself. (...or other policies such as UI.FitComponent and UI.Placement).
      Note that the returned height is dynamically scaled according to the current UI.scale() value. This is to ensure that the icon is rendered at the correct size according to the current DPI settings. If you want the unscaled height, use getBaseHeight().
      Specified by:
      getIconHeight in interface Icon
      Overrides:
      getIconHeight in class ImageIcon
      Returns:
      The height of the icon in component pixel space, or -1 if the icon to indicate an undefined height, which implies that the icon ought to be rendered according to the height of a given component or other properties...
      See Also:
    • getBaseWidth

      public int getBaseWidth()
      Exposes the width of the icon in developer pixels, which is the width that was set when the icon was created or updated using the withIconWidth(int) method.
      Note that this width is not scaled to component pixel space using the current UI.scale() factor. If you want a scaled width, that is more suitable for rendering the icon, use the getIconWidth() method.
      Returns:
      The width of the icon without scaling.
      See Also:
    • getBaseHeight

      public int getBaseHeight()
      Exposes the height of the icon in developer pixels, which is also the height that was set when the icon was created or updated using the withIconHeight(int) method.
      Note that this height is not scaled to component pixel space using the current UI.scale() factor. If you want a scaled height, that is more suitable for rendering the icon, use the getIconHeight() method.
      Returns:
      The height of the icon without scaling.
      See Also:
    • withIconHeight

      public SvgIcon withIconHeight(int newHeight)
      Creates a new SvgIcon with the specified height measured in "developer pixels". The supplied height is developer pixel based, and the existing height-unit in this instance will be overridden to being pixel based in the returned instance.

      This method is useful when you want to adjust the height of an SVG without affecting the (pixel based) width!
      For example, calling icon.withIconHeight(50) on an icon with dimensions 20px×20px will result in an icon that is 20px×50px in size.
      Be aware that using this method may also change the aspect ratio of the icon, potentially causing it to be rendered distorted.


      If the width of this icon is percentage based, then the new icon will have its width overridden to -1 and the unit of the width will also always be pixel based (see widthUnitString() and heightUnitString()). This ensures that percentage-based dimensions are not mixed with explicit pixel dimensions in a single icon instance.

      Parameters:
      newHeight - The height of the icon in developer pixels, or -1 if the icon should be rendered according to the height of a given component or the height of the SVG document itself.
      Returns:
      A new SvgIcon with the given height. If the height is -1, the icon will be rendered according to the height of a given component or the height of the SVG document itself.
      See Also:
    • withIconSize

      public SvgIcon withIconSize(int newWidth, int newHeight)
      Creates a new SvgIcon with the specified width and height measured in "developer pixels". Both supplied dimensions are developer pixel based, and the existing width and height units of this instance will be overridden to being pixel based in the returned instance.

      This method allows you to explicitly set both dimensions of the icon, giving you complete control over its rendered size. However, be mindful that this may distort the icon if the new dimensions don't maintain the original aspect ratio.


      Important: This method implicitly converts any percentage-based dimensions to developer pixel-based dimensions. The conversion preserves the percentage value's intent by resolving it to -1 (unknown) when a negative value is provided. This ensures that percentage-based sizing can be cleared when needed.

      For example, if you have an icon with width="50%" and height="100%", calling withIconSize(100, -1) will result in an icon with width=100px and height=-1 (undefined), allowing the height to be determined by other factors like the component size or aspect ratio.

      Parameters:
      newWidth - The width of the icon in developer pixels, or -1 to indicate an undefined width that should be determined by other factors.
      newHeight - The height of the icon in developer pixels, or -1 to indicate an undefined height that should be determined by other factors.
      Returns:
      A new SvgIcon with the given width and height. Negative values indicate that the dimension should be determined by the component, SVG document, or other layout policies.
      See Also:
    • withIconSize

      public SvgIcon withIconSize(Size size)
      Creates a new SvgIcon with the specified width and height measured in "developer pixels". This method accepts a Size object containing the desired dimensions. Both supplied dimensions are developer pixel based, and the existing width and height units of this instance will be overridden to being pixel based in the returned instance.

      This method allows you to explicitly set both dimensions of the icon using a Size object, giving you complete control over its rendered size. However, be mindful that this may distort the icon if the new dimensions don't maintain the original aspect ratio.


      Important: This method implicitly converts any percentage-based dimensions in the current icon to pixel-based dimensions in the returned icon. The conversion preserves the percentage value's intent by resolving it to -1 (unknown) when a negative value is provided in the Size object. This ensures that percentage-based sizing can be cleared when needed.

      For example, if you have an icon with width="50%" and height="100%", calling withIconSize(Size.of(100, -1)) will result in an icon with width=100px and height=-1 (undefined), allowing the height to be determined by other factors like the component size or aspect ratio.

      The Size object can contain optional dimensions (using Optional semantics), allowing you to specify only width, only height, both, or neither. When a dimension is not present in the Size object, the corresponding dimension in the returned icon will be set to -1 (unknown).

      Parameters:
      size - A Size object containing the desired width and/or height for the icon. Use negative values or empty optionals to indicate that a dimension should remain undefined and be determined by other factors.
      Returns:
      A new SvgIcon with the given width and height from the Size object. Negative values indicate that the dimension should be determined by the component, SVG document, or other layout policies.
      See Also:
    • withIconSizeFromWidth

      public SvgIcon withIconSizeFromWidth(int newWidth)
      Creates a new SvgIcon with the specified width, calculating the height automatically to maintain the aspect ratio of the original SVG document.

      This method is particularly useful when you want to scale an SVG icon proportionally while controlling only one dimension. Unlike withIconWidth(int), which can distort the icon by changing only the width independently, this method preserves the original aspect ratio by calculating the appropriate height.

      Important behaviors and edge cases:
      • If newWidth is negative, returns an icon with both dimensions set to -1 (unknown), effectively resetting to undefined size.
      • If the current icon has percentage-based dimensions (e.g., width="50%"), they are first resolved to pixel values using the SVG document's view box as reference (via withPercentageSizeResolvedAsPixels()) before calculating the aspect ratio.
      • If the SVG document cannot be loaded or has no view box, the original icon is returned unchanged.
      • The resulting icon will always have pixel-based units (PX) for both dimensions, even if the original used percentages.
      • If the calculated height would be fractional, it's rounded up to the nearest integer to prevent clipping.
      • When called on an icon with fixed pixel dimensions, this method simply recalculates the height based on the existing aspect ratio.

      This method is particularly useful in layout scenarios where you need to constrain an icon by width (e.g., fitting within a fixed-width toolbar) while maintaining its visual proportions.

      Parameters:
      newWidth - The desired width in developer pixels. Use -1 to reset to unknown size.
      Returns:
      A new SvgIcon with the specified width and a height calculated to maintain the original aspect ratio. Returns the original icon if the SVG document cannot provide aspect ratio information.
      See Also:
    • withIconSizeFromHeight

      public SvgIcon withIconSizeFromHeight(int newHeight)
      Creates a new SvgIcon with the specified height, calculating the width automatically to maintain the aspect ratio of the original SVG document.

      This method is the counterpart to withIconSizeFromWidth(int) and is useful when you need to control the icon's height while preserving its proportional width. Like its width-based counterpart, this method prevents distortion by maintaining the original aspect ratio.

      Important behaviors and edge cases:
      • If newHeight is negative, returns an icon with both dimensions set to -1 (unknown), effectively resetting to undefined size.
      • If the current icon has percentage-based dimensions (e.g., height="75%"), they are first resolved to pixel values using the SVG document's view box as reference (via withPercentageSizeResolvedAsPixels()) before calculating the aspect ratio.
      • If the SVG document cannot be loaded or has no view box, the original icon is returned unchanged.
      • The resulting icon will always have pixel-based units (PX) for both dimensions, even if the original used percentages.
      • If the calculated width would be fractional, it's rounded up to the nearest integer to prevent clipping.
      • When called on an icon with fixed pixel dimensions, this method simply recalculates the width based on the existing aspect ratio.

      This method is particularly useful in layout scenarios where you need to constrain an icon by height (e.g., fitting within a fixed-height toolbar) while maintaining its visual proportions.

      Parameters:
      newHeight - The desired height in developer pixels. Use -1 to reset to unknown size.
      Returns:
      A new SvgIcon with the specified height and a width calculated to maintain the original aspect ratio. Returns the original icon if the SVG document cannot provide aspect ratio information.
      See Also:
    • withPercentageSizeResolvedAsPixels

      public SvgIcon withPercentageSizeResolvedAsPixels()
      Creates a new SvgIcon where percentage based dimensions are converted to developer pixel based dimensions using the SVG document's view box as reference dimensions. This method is specifically designed for SVG documents with percentage based dimensions. Icons which do not have at least one percentage based dimension are returned as is.

      Consider the following example:

      
            <svg width="100%" height="50%" viewBox="0 0 24 24">
                ...
            </svg>
        
      An SvgIcon with this header will resolve to having the following dimensions: Note that if this SvgIcon is "empty", meaning that it's getSvgDocument() does not return an SVGDocument instance, then this method will also return this instance.
      Returns:
      A new SvgIcon with its percentage based dimensions converted to being pixel based, using the view box of the SVG document as reference frame.
    • getSvgSize

      public Size getSvgSize()
      The underlying SVG document contains a size object, which is the width and height of the root SVG element inside the document.
      Returns:
      The size of the SVG document in the form of a Size.
    • getSvgDocument

      public @Nullable com.github.weisj.jsvg.SVGDocument getSvgDocument()
      Allows you to access the underlying SVGDocument that is used to render the icon.
      Returns:
      The underlying SVGDocument that is used to render the icon.
    • getFitComponent

      public UI.FitComponent getFitComponent()
      Allows you to access the UI.FitComponent policy, which determines if and how the icon should be fitted onto a component when rendered through the paintIcon(Component, Graphics, int, int) method.
      The following fit modes are available: See withFitComponent(UI.FitComponent) if you want to create a new SvgIcon with an updated fit policy.
      Returns:
      The UI.FitComponent that determines if and how the icon should be fitted into a any given component (see paintIcon(Component, Graphics, int, int) ).
    • withFitComponent

      public SvgIcon withFitComponent(UI.FitComponent fit)
      There are different kinds of strategies to fit an SVG icon onto the component. These strategies are identified using the UI.FitComponent enum which defines the following fit modes:
      Parameters:
      fit - The UI.FitComponent that determines if and how the icon should be fitted into a any given component (see paintIcon(Component, Graphics, int, int) ).
      Returns:
      A new SvgIcon with the given UI.FitComponent policy.
    • getPreferredPlacement

      public UI.Placement getPreferredPlacement()
      The preferred placement policy determines where the icon should be placed within a component when rendered through the paintIcon(Component, Graphics, int, int) method.
      Returns:
      The UI.Placement that determines where the icon should be placed within a component (see paintIcon(Component, Graphics, int, int)).
    • withPreferredPlacement

      public SvgIcon withPreferredPlacement(UI.Placement placement)
      Allows you to get an updated SvgIcon with the given UI.Placement policy which determines where the icon should be placed within a component when rendered through the paintIcon(Component, Graphics, int, int) method.
      Parameters:
      placement - The UI.Placement that determines where the icon should be placed within a component (see paintIcon(Component, Graphics, int, int)).
      Returns:
      A new SvgIcon with the given UI.Placement policy.
    • getImage

      public Image getImage()
      Creates a new Image from the SVG document.
      Overrides:
      getImage in class ImageIcon
      Returns:
      A new Image where the SVG document has been rendered into.
    • setImage

      public void setImage(Image image)
      We don't support this. An SVG document is not really an image, it's a vector graphic. Extending ImageIcon is just for compatibility reasons...
      Overrides:
      setImage in class ImageIcon
    • paintIcon

      public void paintIcon(@Nullable Component c, Graphics g, int x, int y)
      Specified by:
      paintIcon in interface Icon
      Overrides:
      paintIcon in class ImageIcon
      Parameters:
      c - The component to render the icon into.
      g - the graphics context
      x - the X coordinate of the icon's top-left corner
      y - the Y coordinate of the icon's top-left corner
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class Object
    • equals

      public boolean equals(Object obj)
      Overrides:
      equals in class Object
    • toString

      public String toString()
      Overrides:
      toString in class ImageIcon