使用batik在JPanel上加载SVG文件

时间:2016-01-08 14:03:48

标签: java swing svg batik

我想用这个简单的代码在JPanel上加载SVG文件,但JPanel是灰色的。我有什么不对吗?

import javax.swing.*;
import org.apache.batik.swing.JSVGCanvas;


public class SVGApplication extends JPanel
{
     public SVGApplication(){


          JSVGCanvas svg = new JSVGCanvas();
          // location of the SVG File
          svg.setURI("file:/C:/Users/Linda/Desktop/test.svg");
          JPanel panel = new JPanel();
          panel.add(svg);
     }

     public static void main(String[] args)
     {
          JFrame frame = new JFrame("SVGView");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new SVGApplication());
          frame.pack();
          frame.setSize(500, 400);
          frame.setVisible(true);
     }
} 

1 个答案:

答案 0 :(得分:2)

您正在向JPanel添加内容,其中一个名为“panel”,它将被添加到任何内容中,因此永远不会显示:

 public SVGApplication(){
      JSVGCanvas svg = new JSVGCanvas();
      // location of the SVG File
      svg.setURI("file:/C:/Users/Linda/Desktop/test.svg");
      JPanel panel = new JPanel(); // *** what is this for? ***
      panel.add(svg);  // **** you never add this panel to anything ****
 }

摆脱面板:

 public SVGApplication(){
      JSVGCanvas svg = new JSVGCanvas();
      // location of the SVG File
      svg.setURI("file:/C:/Users/Linda/Desktop/test.svg");
      // JPanel panel = new JPanel(); // *** what is this for? ***
      // panel.add(svg);
      add(svg);
 }

更好的是,为什么不简单地使用JSVGCanvas组件?为什么要将它包装在SVGApplication面板中?