Reputation: 161
I have to generate line chart for export (save as png) without displaying the chart. I used existing example from JavaFX site. Is this right way to do it ?
Here is the sample program used to generate png image,
public class FxChartDemo extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
stage.setTitle("Line Chart Sample");
//defining the axes
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Number of Month");
xAxis.setLabel("Number of Month");
//creating the chart
LineChart<Number, Number> lineChart =
new LineChart<Number, Number>(xAxis, yAxis);
lineChart.setTitle("Stock Monitoring, 2010");
//defining a series
XYChart.Series series = new XYChart.Series();
series.setName("My portfolio");
//populating the series with data
series.getData().add(new XYChart.Data(1, 23));
series.getData().add(new XYChart.Data(2, 14));
series.getData().add(new XYChart.Data(3, 15));
series.getData().add(new XYChart.Data(4, 24));
series.getData().add(new XYChart.Data(5, 34));
Scene scene = new Scene(lineChart, 800, 600);
lineChart.setAnimated(false);
lineChart.getData().add(series);
saveAsPng(lineChart, "c:\\temp\\chart.png");
stage.setScene(scene);
saveAsPng(lineChart, "c:\\temp\\chart1.png");
//stage.show();
System.out.println("After show");
}
public void saveAsPng(LineChart lineChart, String path) {
WritableImage image = lineChart.snapshot(new SnapshotParameters(), null);
File file = new File(path);
try {
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Upvotes: 3
Views: 10783
Reputation: 143
No, it doesn`t work. You should try change this code:
......
saveAsPng(lineChart, "c:\\temp\\chart.png");
stage.setScene(scene);
saveAsPng(lineChart, "c:\\temp\\chart1.png");
//stage.show();
System.out.println("After show");
}
public void saveAsPng(LineChart lineChart, String path) {
WritableImage image = lineChart.snapshot(new SnapshotParameters(), null);
......
to:
......
saveAsPng(scene, "c:\\temp\\chart.png");
stage.setScene(scene);
saveAsPng(scene, "c:\\temp\\chart1.png");
//stage.show();
System.out.println("After show");
}
public void saveAsPng(Scene scene, String path) {
WritableImage image = scene.snapshot(null);
......
works perfect for me.
Upvotes: 5