---
title: "svg桌面应用程序（一）"
author: "skymr"
date: "2012-06-25T10:48:03Z"
tags: []
categories: ["编程语言"]
slug: "svg"
draft: false
lastmod: "2012-06-25T10:48:03Z"
id: 1567037
url: "https://skymr.iteye.com/blog/1567037"
---

**在java中显示svg图**

 

下载bakit工程

[http://xmlgraphics.apache.org/batik/download.cgi](http://xmlgraphics.apache.org/batik/download.cgi)

介绍

[http://xmlgraphics.apache.org/batik/index.html](http://xmlgraphics.apache.org/batik/index.html)

 

 创建svg文档对象

 

```
		String parser = XMLResourceDescriptor.getXMLParserClassName();
		SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
		File file = new File("bin/com/longshine/svg/ui/3D.svg");
			Document indexDoc = f.createDocument(file.toURL().toString());
```

 

 

在swing面板中加入文档对象显示 

 

```
			JSVGCanvas canvas = new JSVGCanvas();//用于显示svg图
			canvas.setBackground(Color.BLACK);
			canvas.setVisible(true);
			canvas.setBounds(0, 0, 800, 600);

		canvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
		canvas.setDocument(indexDoc);
		this.add(canvas);//swing面板中加入画布
```

 

 

![](http://dl.iteye.com/upload/attachment/0069/8976/2fe81390-72a6-3f05-ba84-ebafc495222c.png)

 

 

 

 

 

 

 

 

 

 

```
package com.longshine.svg.ui;

import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.swing.JFrame;

import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.Document;

public class SVGUIApp extends JFrame{

	public void init(){
		this.setBounds(0, 0, 800, 600);
		this.setDefaultCloseOperation(3);
		this.setVisible(true);
		String parser = XMLResourceDescriptor.getXMLParserClassName();
		SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
		File file = new File("bin/com/longshine/svg/ui/3D.svg");
		try {
			Document indexDoc = f.createDocument(file.toURL().toString());
			JSVGCanvas canvas = new JSVGCanvas();
			canvas.setBackground(Color.BLACK);
			canvas.setVisible(true);
			canvas.setBounds(0, 0, 800, 600);

		canvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
		canvas.setDocument(indexDoc);
		this.add(canvas);

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	public static void main(String[] args){
		new SVGUIApp().init();
	}
}
```