Manipulate SVG DOM during loading
masterYou can modify SVG elements (e.g., changing colors or attributes) before they are fully parsed by using a DomProcessor via the LoaderContext.
To implement this:
- Implement the
DomProcessorinterface and override theprocess(DomElement root)method. - Inside
process, useelement.attribute(name, default)to read attributes andelement.setAttribute(name, value)to modify them. - To inject custom dynamic values (like a color that changes at runtime), use
document.registerNamedElement(id, paint)and then set the element's attribute to thatid. - Pass the processor to the loader using
LoaderContext.builder().preProcessor(processor).build().
// 1. Define a processor
CustomColorsProcessor processor = new CustomColorsProcessor(List.of("myRect"));
// 2. Load with the processor
SVGLoader loader = new SVGLoader();
SVGDocument document = loader.load(svgUrl, LoaderContext.builder().preProcessor(processor).build());
// 3. Update the dynamic value later
DynamicAWTSvgPaint dynamicColor = processor.customColorForId("myRect");
dynamicColor.setColor(Color.RED);
// Then call repaint() on your component