I'm using Batik (svg-gen) to draw a svg (technical) diagram with the aid of java awt in a back-end service. I use this service on many places were the need arises to draw such diagram.
I would like to use a "tool-tip-kind-of-hover-over" to give more details on for instance a rectangle in the diagram.
Is this possible in Batik? I've found some hints on using css style but it strikes me as tricky.
I found out that its done by title, like described here. In order to include the title tag, the Batik classes that generate SVG and relevant AWT classes can be extended.
To start:
@Getter
public class TitledRectangle extends Rectangle {
private String title;
public TitledRectangle() {
}
public TitledRectangle(TitledRectangle r) {
super( r );
this.title = r.title;
}
// other constructors
}
And the corresponding batik class
public class PDSvgTitledRectangle extends SVGRectangle {
public PDSvgTitledRectangle(SVGGeneratorContext generatorContext) {
super( generatorContext );
}
public Element toSVG(TitledRectangle rect) {
Element element = super.toSVG( rect );
if ( rect.getTitle() != null ) {
Element svgTitle = super.generatorContext.getDOMFactory().createElementNS( "http://www.w3.org/2000/svg", "title" );
svgTitle.setTextContent( rect.getTitle() );
element.appendChild( svgTitle );
}
return element;
}
}
Now the new shape converter has to be used. That can be achieved by extending the SVGShape, responsible for writing the svg xml.
public class PDSvgShape extends SVGShape {
private PDSvgTitledRectangle titledRectangle;
public PDSvgShape(SVGGeneratorContext generatorContext) {
super( generatorContext );
titledRectangle = new PDSvgTitledRectangle( generatorContext );
}
public Element toSVG(Shape shape) {
if ( shape instanceof TitledRectangle ) {
return this.titledRectangle.toSVG( (TitledRectangle) shape );
}
return super.toSVG( shape );
}
}
And writing your own SVGGraphics2D (extending the existing one)
public class PDSvgGraphics2D extends SVGGraphics2D {
public PDSvgGraphics2D(Document domFactory) {
super( domFactory );
super.shapeConverter = new PDSvgShape( super.generatorCtx );
}
public PDSvgGraphics2D(Document domFactory, ImageHandler imageHandler, ExtensionHandler extensionHandler, boolean textAsShapes) {
super( domFactory, imageHandler, extensionHandler, textAsShapes );
super.shapeConverter = new PDSvgShape( buildSVGGeneratorContext( domFactory, imageHandler, extensionHandler ) );
}
public PDSvgGraphics2D(SVGGeneratorContext generatorCtx, boolean textAsShapes) {
super( generatorCtx, textAsShapes );
super.shapeConverter = new PDSvgShape( generatorCtx );
}
public PDSvgGraphics2D(PDSvgGraphics2D g) {
super( g );
super.shapeConverter = g.shapeConverter;
}
}
Now, there's the possibility to use the newly created awt extension:
PDSvgGraphics2D g = new PDSvgGraphics2D( ctx, false );
TitledRectangle rect = new TitledRectangle( x, y, w, h, "hello world!" ).
g.draw( rectangle );