Package swingtree.api

Interface IconDeclaration


@Immutable public interface IconDeclaration
Primarily designed to be implemented by an Enum type that declares a set of icon paths so that the enum instances can be used to identify and load (cached) icons across your application.

Here an example of how to use this interface:


 public enum Icons implements IconDeclaration
 {
     ADD("icons/add.png"),
     REMOVE("icons/remove.png"),
     EDIT("icons/edit.png"),
     SAVE("icons/save.png"),
     CANCEL("icons/cancel.png"),
     REFRESH("icons/refresh.png");
     // ...

     private final String path;

     Icons(String path) { this.path = path; }

     {@literal @}Override public String source() {
         return path;
     }
 }
 
You may then use the enum instances in the SwingTree API just like you would use the ImageIcon class:

  UI.button(Icons.ADD)
  .onClick( it -> vm.add() )
  
The reason why enums should be used instead of Strings is so that you have some more compile time safety in your application! When it comes to resource loading Strings are brittle because they are susceptible to typos and refactoring mistakes.

Instances of this class are intended to be used as part of a view model instead of using the Icon or ImageIcon classes directly.

The reason for this is the fact that traditional Swing icons are often heavyweight objects whose loading may or may not succeed, and so they are not suitable for direct use in a property as part of your view-model. Instead, you should use this IconDeclaration interface, which is a lightweight value object that merely models the resource location of the icon even if it is not yet loaded or even does not exist at all.

Not only does this make your view model more robust, but it also allows you to write unit tests much more easily. You can create icon declarations even if the targeted icon may not be available at all, yet you can still test the behavior of your view-model.

SVG Support: In addition to traditional image files, IconDeclaration supports programmatically defined SVG icons through the ofAutoScaledSvg(String) factory method. This enables creation of resolution-independent vector icons directly in code:


  // Create a custom SVG icon declaration
  IconDeclaration playButton = IconDeclaration.ofSvg(
      "<svg width='24' height='24' viewBox='0 0 24 24'>" +
      "  <path d='M8 5v14l11-7z' fill='currentColor'/>" +
      "</svg>"
  );

  // Use it in UI declarations
  UI.button(playButton)
    .onClick(it -> mediaPlayer.play())
  
SVG icons automatically scale to match DPI settings and maintain crisp edges at any resolution. They can be sized dynamically or set to a fixed size using withSize(Size).
  • Method Details

    • source

      String source()
      This method supplies a String which is a "source" for producing ImageIcon, this is typically a path to a file, but may also be a full-blown SVG document in text form.
      The exact meaning of the source String is defined by the IconDeclaration.SourceFormat returned by sourceFormat() method. Together, these two properties form the most important part an icon declaration, since they constitute the minimum amount of information needed to resolve an actual icon...
      Note that in case of the source String being a IconDeclaration.SourceFormat.PATH_TO_ICON, it may either be a path relative to the classpath or may be an absolute path.
      Returns:
      The "source String" which is used together with the sourceFormat() to resolve an icon. It is typically a path to the icon resource, which is relative to the classpath or may be an absolute path.
    • sourceFormat

      default IconDeclaration.SourceFormat sourceFormat()
      Returns the format of the source string returned by source(). This determines how the source string should be interpreted when loading or creating the icon.

      By default, this method returns IconDeclaration.SourceFormat.PATH_TO_ICON, meaning the source string is treated as a file path. Implementations can override this method to return IconDeclaration.SourceFormat.SVG_STRING if they provide SVG content directly.

      Returns:
      The format of the source string, never null.
    • size

      default Optional<Size> size()
      The preferred size of the icon, which is not necessarily the actual size of the icon that is being loaded but rather the size that the icon should be scaled to when it is being loaded.
      If this method returns Optional.empty(), then the loaded icon will have the exact same size found at the image file found at source(). A non-empty optional with a Size.unknown(), specifically indicates to SvgIcons that their size should be context dependent, meaning that their SvgIcon.getIconWidth() and SvgIcon.getIconHeight() are both returning -1 to indicate flexible scaling.
      In case of a regular png or jpeg on the other hand, a Size.unknown() will also cause the resulting ImageIcon to have the same dimensions found in the file.
      Returns:
      The preferred size of the icon or Optional.empty() if the size is unspecified, which means that the icon should be loaded in its original size. A non-empty optional with a Size.unknown(), specifically indicates to SvgIcons that their size should be context dependent.
    • find

      default Optional<ImageIcon> find()
      This method is used to find the icon resource and load it as an ImageIcon instance wrapped in an Optional, or return an empty Optional if the icon resource could not be found.
      Returns:
      An Optional that contains the ImageIcon if the icon resource was found, otherwise an empty Optional.
    • withSize

      default IconDeclaration withSize(Size size)
      Creates and returns an updated IconDeclaration instance with a new preferred size for the icon.
      Parameters:
      size - The preferred size of the icon in the form of a Size instance.
      Returns:
      A new IconDeclaration instance with the same path but with the given size.
    • withSize

      default IconDeclaration withSize(int width, int height)
      Creates and returns an updated IconDeclaration instance with a new preferred width and height for the icon.
      Parameters:
      width - The preferred width of the icon.
      height - The preferred height of the icon.
      Returns:
      A new IconDeclaration instance with the same path but with the specified width and height as preferred size.
    • withWidth

      default IconDeclaration withWidth(int width)
      Creates and returns an updated IconDeclaration instance with a new preferred width for the icon.
      Parameters:
      width - The preferred width of the icon.
      Returns:
      A new IconDeclaration instance with the same path but with the specified width as preferred width.
    • withHeight

      default IconDeclaration withHeight(int height)
      Allows you to create an updated IconDeclaration instance with a new preferred height for the icon.
      Parameters:
      height - The preferred height of the icon.
      Returns:
      A new IconDeclaration instance with the same path but with the specified height as preferred height.
    • find

      default <T extends ImageIcon> Optional<T> find(Class<T> type)
      This method is used to find an ImageIcon of a specific type and load and return it wrapped in an Optional, or return an empty Optional if the icon resource could not be found.
      Type Parameters:
      T - The type of icon to find.
      Parameters:
      type - The type of icon to find.
      Returns:
      An Optional that contains the ImageIcon of the given type.
    • of

      static IconDeclaration of(String path)
      A factory method for creating an IconDeclaration instance from the provided path to the icon resource.
      Parameters:
      path - The path to the icon resource, which may be relative to the classpath or may be an absolute path.
      Returns:
      A new IconDeclaration instance that represents the given icon resource as a constant.
    • of

      static IconDeclaration of(Size size, String path)
      A factory method for creating an IconDeclaration instance from the provided path to the icon resource and the preferred size.
      Parameters:
      size - The preferred size of the icon.
      path - The path to the icon resource, which may be relative to the classpath or may be an absolute path.
      Returns:
      A new IconDeclaration instance that represents the given icon resource as a constant.
    • ofAutoScaledSvg

      static IconDeclaration ofAutoScaledSvg(String svg)
      Creates an IconDeclaration instance from an SVG document string, which will be resolved to an SvgIcon with an unknown size, effectively making it scale depending on its usage context. This factory method is specifically designed for creating vector-based icons programmatically without requiring external files.

      The provided SVG string must be a complete, well-formed SVG XML document. The resulting icon declaration will have its sourceFormat() set to IconDeclaration.SourceFormat.SVG_STRING.

      Icon declarations produced by this method will resolve to SvgIcon instances, which support dynamic scaling while maintaining crisp edges at any scale.

      Example:

      
       String checkmarkSvg = "<svg width='16' height='16'>" +
                             "<path d='M2 8l4 4l8-8' stroke='green' stroke-width='2' fill='none'/>" +
                             "</svg>";
       IconDeclaration checkmark = IconDeclaration.ofAutoScaledSvg(checkmarkSvg)
                                                  .withSize(24, 24);
       
      In the above example, an SvgIcon loaded using this declaration will report -1 for both SvgIcon.getIconWidth() and SvgIcon.getIconHeight() instead of 16! This is to ensure that the svg is scalable when used as component icons...
      Parameters:
      svg - The complete SVG document as a string. Must not be null.
      Returns:
      A new IconDeclaration instance representing the SVG icon.
      Throws:
      NullPointerException - if svg is null.
    • ofSvg

      static IconDeclaration ofSvg(String svg)
      Creates an IconDeclaration instance from an SVG document string, which will be resolved to an SvgIcon with the same size declared in the SVG text. This factory method is specifically designed for creating vector-based icons programmatically without requiring external files.

      The provided SVG string must be a complete, well-formed SVG XML document. The resulting icon declaration will have its sourceFormat() set to IconDeclaration.SourceFormat.SVG_STRING.

      Icon declarations produced by this method will resolve to SvgIcon instances, which support dynamic scaling while maintaining crisp edges at any scale.

      Example:

      
       String checkmarkSvg = "<svg width='16' height='16'>" +
                             "<path d='M2 8l4 4l8-8' stroke='green' stroke-width='2' fill='none'/>" +
                             "</svg>";
       IconDeclaration checkmark = IconDeclaration.ofSvg(checkmarkSvg)
                                                  .withSize(24, 24);
       
      In the above example, an SvgIcon loaded using this declaration will report 16 for both SvgIcon.getIconWidth() and SvgIcon.getIconHeight().
      Parameters:
      svg - The complete SVG document as a string. Must not be null.
      Returns:
      A new IconDeclaration instance representing the SVG icon.
      Throws:
      NullPointerException - if svg is null.
    • of

      static IconDeclaration of(Size size, IconDeclaration.SourceFormat sourceFormat, String source)
      Creates an IconDeclaration instance with full control over all declaration properties: size, source format, and source content.

      This is the most comprehensive factory method, allowing precise specification of how the icon should be interpreted and displayed. It's particularly useful when creating icon declarations programmatically or when you need explicit control over the source format.

      Size Handling: If the provided size parameter is Size.unknown(), it will indicate to raster based icons that they should use their natural dimensions (for raster images), whereas SVG based icons will be loaded without any size to make their size effectively context-dependent (automatic scaling).

      Example Usage:

      
        // Create a PNG icon declaration with specific size
        IconDeclaration icon1 = IconDeclaration.of(
            Size.of(32, 32),
            SourceFormat.PATH_TO_ICON,
            "icons/user.png"
        );
      
        // Create an SVG icon declaration with unknown (flexible) size
        IconDeclaration icon2 = IconDeclaration.of(
            Size.unknown(),
            SourceFormat.SVG_STRING,
            "<svg ...>...</svg>"
        );
        
      Parameters:
      size - The preferred display size for the icon. Use Size.unknown() to indicate natural/context-dependent sizing. Must not be null.
      sourceFormat - The format interpretation of the source string. Must not be null.
      source - The icon source content (file path or SVG XML). Must not be null.
      Returns:
      A new IconDeclaration instance configured with the specified properties.
      Throws:
      NullPointerException - if any parameter is null.
      See Also: