Class SvgIcon
- All Implemented Interfaces:
Serializable,Accessible,Icon
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:
-
Nested Class Summary
Nested classes/interfaces inherited from class javax.swing.ImageIcon
ImageIcon.AccessibleImageIcon -
Field Summary
-
Method Summary
Modifier and TypeMethodDescriptionstatic SvgIconTries to create anSvgIconfrom a resource path defined by the supplied string.static SvgIconCreates anSvgIconfrom a resource path and a custom size.static SvgIconCreates anSvgIconfrom the supplied URL pointing to an SVG document.static SvgIconbooleanintExposes the height of the icon in developer pixels, which is also the height that was set when the icon was created or updated using thewithIconHeight(int)method.
Note that this height is not scaled to component pixel space using the currentUI.scale()factor.intExposes the width of the icon in developer pixels, which is the width that was set when the icon was created or updated using thewithIconWidth(int)method.
Note that this width is not scaled to component pixel space using the currentUI.scale()factor.Allows you to access theUI.FitComponentpolicy, which determines if and how the icon should be fitted onto a component when rendered through thepaintIcon(Component, Graphics, int, int)method.
The following fit modes are available:UI.FitComponent.NO- The image will not be scaled to fit the inner component area.intExposes 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.intExposes 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.getImage()Creates a newImagefrom the SVG document.The preferred placement policy determines where the icon should be placed within a component when rendered through thepaintIcon(Component, Graphics, int, int)method.@Nullable com.github.weisj.jsvg.SVGDocumentAllows you to access the underlyingSVGDocumentthat is used to render the icon.The underlying SVG document contains a size object, which is the width and height of the root SVG element inside the document.inthashCode()Returns the unit of the height of the icon or an emptyStringif the encountered unit is unknown.static SvgIconof(com.github.weisj.jsvg.SVGDocument svgDocument) Allows you to create anSvgIconfrom an already loadedSVGDocument.static SvgIconAllows you to create anSvgIconfrom an already loadedSVGDocumentwith a custom width and height defined by the suppliedSize.
If you want to customize the layout and placement of the icon, consider creating derived versions using thewithFitComponent(UI.FitComponent)andwithPreferredPlacement(UI.Placement)methods.static SvgIconof(InputStream stream) Reads the SVG document from the supplied input stream and creates anSvgIconfrom it.static SvgIconof(InputStream stream, Size size) static SvgIconAllows you to directly create anSvgIconfrom a string containing an SVG text.static SvgIconvoidvoidWe don't support this.toString()Returns the unit of the width of the icon or an emptyStringif the encountered unit is unknown.There are different kinds of strategies to fit an SVG icon onto the component.withIconHeight(int newHeight) Creates a newSvgIconwith the specified height measured in "developer pixels".withIconSize(int newWidth, int newHeight) Creates a newSvgIconwith the specified width and height measured in "developer pixels".withIconSize(Size size) Creates a newSvgIconwith the specified width and height measured in "developer pixels".withIconSizeFromHeight(int newHeight) Creates a newSvgIconwith the specified height, calculating the width automatically to maintain the aspect ratio of the original SVG document.withIconSizeFromWidth(int newWidth) Creates a newSvgIconwith the specified width, calculating the height automatically to maintain the aspect ratio of the original SVG document.withIconWidth(int newWidth) Creates an updatedSvgIconwith a new width measured in "developer pixel", which effectively translates to what is being reported bygetBaseWidth(), and indirectly alsogetIconWidth()(which is scaled to component pixel space).Creates a newSvgIconwhere percentage based dimensions are converted to developer pixel based dimensions using the SVG document's view box as reference dimensions.withPreferredPlacement(UI.Placement placement) Allows you to get an updatedSvgIconwith the givenUI.Placementpolicy which determines where the icon should be placed within a component when rendered through thepaintIcon(Component, Graphics, int, int)method.Methods inherited from class javax.swing.ImageIcon
getAccessibleContext, getDescription, getImageLoadStatus, getImageObserver, loadImage, setDescription, setImageObserver
-
Method Details
-
at
Tries to create anSvgIconfrom a resource path defined by the supplied string.- Parameters:
path- The path to the SVG document.- Returns:
- A new
SvgIconcreated from the SVG found at the given path.
-
at
Creates anSvgIconfrom a resource path and a custom size. -
at
Creates anSvgIconfrom 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 (seepaintIcon(Component, Graphics, int, int)).- Parameters:
svgUrl- The URL to the SVG document.- Returns:
- A new
SvgIconcreated from the SVG found at the supplied URL.
-
at
-
of
Allows you to directly create anSvgIconfrom a string containing an SVG text. -
of
-
of
Reads the SVG document from the supplied input stream and creates anSvgIconfrom 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 (seepaintIcon(Component, Graphics, int, int)). If you want to customize the size, layout and placement of the icon, consider creating derived versions using thewithIconWidth(int),withIconHeight(int),withIconSize(int, int),withFitComponent(UI.FitComponent)andwithPreferredPlacement(UI.Placement)methods.- Parameters:
stream- The input stream supplying the text data of the SVG document.
-
of
Reads the SVG document from the supplied input stream and creates anSvgIconfrom it with a custom width and height defined by the suppliedSize.
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 (seepaintIcon(Component, Graphics, int, int)).
If you want to customize the layout and placement of the icon, consider creating derived versions using thewithFitComponent(UI.FitComponent)andwithPreferredPlacement(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 aSize.
-
of
Allows you to create anSvgIconfrom an already loadedSVGDocument. 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 (seepaintIcon(Component, Graphics, int, int)). If you want to customize the size, layout and placement of the icon, consider creating derived versions using thewithIconWidth(int),withIconHeight(int),withIconSize(int, int),withFitComponent(UI.FitComponent)andwithPreferredPlacement(UI.Placement)methods.- Parameters:
svgDocument- The already loaded SVG document, which will be used to render the icon.
-
of
Allows you to create anSvgIconfrom an already loadedSVGDocumentwith a custom width and height defined by the suppliedSize.
If you want to customize the layout and placement of the icon, consider creating derived versions using thewithFitComponent(UI.FitComponent)andwithPreferredPlacement(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 aSize.
-
widthUnitString
Returns the unit of the width of the icon or an emptyStringif 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
Returns the unit of the height of the icon or an emptyStringif 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 asUI.FitComponentandUI.Placement).
Note that the returned width is dynamically scaled according to the currentUI.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, usegetBaseWidth().- Specified by:
getIconWidthin interfaceIcon- Overrides:
getIconWidthin classImageIcon- 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
Creates an updatedSvgIconwith a new width measured in "developer pixel", which effectively translates to what is being reported bygetBaseWidth(), and indirectly alsogetIconWidth()(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 instanceThis method is useful when you want to adjust the width of an SVG without affecting the (pixel based) height!
For example, callingicon.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
-1and the unit of the height will also always be pixel based (seewidthUnitString()andheightUnitString()).- 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
SvgIconwith 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 asUI.FitComponentandUI.Placement).
Note that the returned height is dynamically scaled according to the currentUI.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, usegetBaseHeight().- Specified by:
getIconHeightin interfaceIcon- Overrides:
getIconHeightin classImageIcon- 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 thewithIconWidth(int)method.
Note that this width is not scaled to component pixel space using the currentUI.scale()factor. If you want a scaled width, that is more suitable for rendering the icon, use thegetIconWidth()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 thewithIconHeight(int)method.
Note that this height is not scaled to component pixel space using the currentUI.scale()factor. If you want a scaled height, that is more suitable for rendering the icon, use thegetIconHeight()method.- Returns:
- The height of the icon without scaling.
- See Also:
-
withIconHeight
Creates a newSvgIconwith 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, callingicon.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
-1and the unit of the width will also always be pixel based (seewidthUnitString()andheightUnitString()). 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
SvgIconwith 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
Creates a newSvgIconwith 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
SvgIconwith 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
Creates a newSvgIconwith the specified width and height measured in "developer pixels". This method accepts aSizeobject 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
Sizeobject, 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
Sizeobject. 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
Sizeobject can contain optional dimensions (usingOptionalsemantics), allowing you to specify only width, only height, both, or neither. When a dimension is not present in theSizeobject, the corresponding dimension in the returned icon will be set to -1 (unknown).- Parameters:
size- ASizeobject 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
SvgIconwith the given width and height from theSizeobject. Negative values indicate that the dimension should be determined by the component, SVG document, or other layout policies. - See Also:
-
withIconSizeFromWidth
Creates a newSvgIconwith 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
Important behaviors and edge cases: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.- If
newWidthis 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
SvgIconwith 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:
- If
-
withIconSizeFromHeight
Creates a newSvgIconwith the specified height, calculating the width automatically to maintain the aspect ratio of the original SVG document.This method is the counterpart to
Important behaviors and edge cases: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.- If
newHeightis 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
SvgIconwith 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:
- If
-
withPercentageSizeResolvedAsPixels
Creates a newSvgIconwhere 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:
An<svg width="100%" height="50%" viewBox="0 0 24 24"> ... </svg>SvgIconwith this header will resolve to having the following dimensions:getIconWidth()== 24getIconHeight()== 12
SvgIconis "empty", meaning that it'sgetSvgDocument()does not return anSVGDocumentinstance, then this method will also return this instance.- Returns:
- A new
SvgIconwith its percentage based dimensions converted to being pixel based, using the view box of the SVG document as reference frame.
-
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 underlyingSVGDocumentthat is used to render the icon.- Returns:
- The underlying
SVGDocumentthat is used to render the icon.
-
getFitComponent
Allows you to access theUI.FitComponentpolicy, which determines if and how the icon should be fitted onto a component when rendered through thepaintIcon(Component, Graphics, int, int)method.
The following fit modes are available:UI.FitComponent.NO- The image will not be scaled to fit the inner component area.UILayoutConstants.WIDTH(int, int, int)- The image will be scaled to fit the inner component width.UILayoutConstants.HEIGHT(int, int, int)- The image will be scaled to fit the inner component height.UI.FitComponent.WIDTH_AND_HEIGHT- The image will be scaled to fit both the component width and height.UI.FitComponent.MAX_DIM- The image will be scaled to fit the larger of the two dimensions of the inner component area.UI.FitComponent.MIN_DIM- The image will be scaled to fit the smaller of the two dimensions of the inner component area.UI.FitComponent.UNDEFINED- How the image will be scaled to fit the component is unclear. Another property may override this, but typically the behavior is similar toUI.FitComponent.NO.
withFitComponent(UI.FitComponent)if you want to create a newSvgIconwith an updated fit policy.- Returns:
- The
UI.FitComponentthat determines if and how the icon should be fitted into a any given component (seepaintIcon(Component, Graphics, int, int)).
-
withFitComponent
There are different kinds of strategies to fit an SVG icon onto the component. These strategies are identified using theUI.FitComponentenum which defines the following fit modes:UI.FitComponent.NO- The image will not be scaled to fit the inner component area.UILayoutConstants.WIDTH(int, int, int)- The image will be scaled to fit the inner component width.UILayoutConstants.HEIGHT(int, int, int)- The image will be scaled to fit the inner component height.UI.FitComponent.WIDTH_AND_HEIGHT- The image will be scaled to fit both the component width and height.UI.FitComponent.MAX_DIM- The image will be scaled to fit the larger of the two dimension of the inner component area.UI.FitComponent.MIN_DIM- The image will be scaled to fit the smaller of the two dimension of the inner component area.
- Parameters:
fit- TheUI.FitComponentthat determines if and how the icon should be fitted into a any given component (seepaintIcon(Component, Graphics, int, int)).- Returns:
- A new
SvgIconwith the givenUI.FitComponentpolicy.
-
getPreferredPlacement
The preferred placement policy determines where the icon should be placed within a component when rendered through thepaintIcon(Component, Graphics, int, int)method.- Returns:
- The
UI.Placementthat determines where the icon should be placed within a component (seepaintIcon(Component, Graphics, int, int)).
-
withPreferredPlacement
Allows you to get an updatedSvgIconwith the givenUI.Placementpolicy which determines where the icon should be placed within a component when rendered through thepaintIcon(Component, Graphics, int, int)method.- Parameters:
placement- TheUI.Placementthat determines where the icon should be placed within a component (seepaintIcon(Component, Graphics, int, int)).- Returns:
- A new
SvgIconwith the givenUI.Placementpolicy.
-
getImage
Creates a newImagefrom the SVG document. -
setImage
We don't support this. An SVG document is not really an image, it's a vector graphic. ExtendingImageIconis just for compatibility reasons... -
paintIcon
-
hashCode
public int hashCode() -
equals
-
toString
-