Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load SVG file in a Button on JavaFX

I have an SVG image created in Inkscape. I put it in the same directory as my class.

Is there a way to load that image and convert it to an SVG Path?

The idea behind this is to get that image with getClass().getResource("image.svg").toExternalForm() and convert it to a SVGPath for the imageSVG.setContent() method. After of that I want to put that SVGPath object in a Button with the button.setGraphic() method.

I don't want to use Transcoders or BufferedImage class.

like image 465
Deus Arcana Avatar asked Oct 17 '16 03:10

Deus Arcana


1 Answers

With the SvgLoader provided by https://github.com/afester/FranzXaver, you can simply load an SVG file as a JavaFX node and set it on the button as its graphic:

...
    // load the svg file
    InputStream svgFile = 
          getClass().getResourceAsStream("/afester/javafx/examples/data/Ghostscript_Tiger.svg");
    SvgLoader loader = new SvgLoader();
    Group svgImage = loader.loadSvg(svgFile);

    // Scale the image and wrap it in a Group to make the button 
    // properly scale to the size of the image  
    svgImage.setScaleX(0.1);
    svgImage.setScaleY(0.1);
    Group graphic = new Group(svgImage);

    // create a button and set the graphics node
    Button button = new Button();
    button.setGraphic(graphic);

    // add the button to the scene and show the scene
    HBox layout = new HBox(button);
    HBox.setMargin(button, new Insets(10));
    Scene scene = new Scene(layout);
    primaryStage.setScene(scene);
    primaryStage.show();
...

Screenshot of image on button

like image 150
Andreas Fester Avatar answered Sep 19 '22 21:09

Andreas Fester