Skip to main content

Dynamic SVGIcon demo

This is a minimal program which demonstrates a correct way to create SVG Icons and render them to the screen. This particular example generates the SVG document dynamically. You can also load SVG documents from file.

This example can be found in the SVG Salamnder source.


package com.kitfox.svg.example;

import java.awt.*;
import java.net.*;
import java.io.*;
import javax.swing.*;

import com.kitfox.svg.*;
import com.kitfox.svg.app.beans.*;


class IconPanel extends JPanel
{
    public static final long serialVersionUID = 0;
    
    final SVGIcon icon;
    
    
    public IconPanel()
    {
        StringReader reader = new StringReader(makeDynamicSVG());
        URI uri = SVGCache.getSVGUniverse().loadSVG(reader, "myImage"); 
        icon = new SVGIcon();
        icon.setSvgURI(uri);
        
        setPreferredSize(new Dimension(400, 400));
    }
    
    public void paintComponent(Graphics g)
    {
        final int width = getWidth();
        final int height = getHeight();
        
        g.setColor(getBackground());
        g.fillRect(0, 0, width, height);
        
        icon.paintIcon(this, g, 0, 0);
    }
    
    private String makeDynamicSVG()
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        
        pw.println("<svg width=\"400\" height=\"400\" style=\"fill:none;stroke-width:4\">");
        pw.println("    <circle cx=\"200\" cy=\"200\" r=\"200\" style=\"stroke:blue\"/>");
        pw.println("    <circle cx=\"140\" cy=\"140\" r=\"40\" style=\"stroke:red\"/>");
        pw.println("    <circle cx=\"260\" cy=\"140\" r=\"40\" style=\"stroke:red\"/>");
        pw.println("    <polyline points=\"100 300 150 340 250 240 300 300\" style=\"stroke:red\"/>");
        pw.println("</svg>");
        
        pw.close();
        return sw.toString();
    }
}

/**
 *
 * @author  kitfox
 */
public class SVGIODemoFrame extends javax.swing.JFrame
{
    public static final long serialVersionUID = 0;
    
    IconPanel panel = new IconPanel();
    
    /** Creates new form SVGIconDemo */
    public SVGIODemoFrame()
    {
        initComponents();

        this.getContentPane().add(panel, BorderLayout.CENTER);
        
        pack();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents()
    {

        setLayout(new java.awt.BorderLayout());

    }
    
    public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new SVGIODemoFrame().setVisible(true);
            }
        });
    }
    
}
 
 
Close
loading
Please Confirm
Close