edu.makery.ch

Education in the Making.

JavaFX Snapshot as PNG Image

JavaFX 2.2 and above provides a convenient snapshot feature. It takes a snapshot of any node or scene.

The following method saves the barChart node as a png image:

1
2
3
4
5
6
7
8
9
10
11
12
13
@FXML
public void saveAsPng() {
  WritableImage image = barChart.snapshot(new SnapshotParameters(), null);
  
  // TODO: probably use a file chooser here
  File file = new File("chart.png");
  
    try {
        ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
    } catch (IOException e) {
      // TODO: handle exception here
    }
}

Note: You could test this code with our AddressApp example (see download at the end of AddressApp Tutorial Part VII). Just add the saveAsPng() method to the BirthdayStatisticsController class and call the method through some action (e.g. a new button).

Comments