JavaFX 2.2 and above provides a convenient screenshot feature. It takes a snapshot of any node or scene.
The following method saves the barChart
node as a png
image:
@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 in AddressApp Tutorial Part 7). Just add the saveAsPng()
method to the BirthdayStatisticsController
class and call the method through some action (e.g. a new button).