Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX I want to save Chart-Image completely

Tags:

javafx

charts

This is my code:

public class SceneToImageAndWrite extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        stage.setTitle("Primary Stage");

        final CategoryAxis xAxis = new CategoryAxis();
        xAxis.setLabel("Animals");
        final NumberAxis yAxis = new NumberAxis();
        yAxis.setLabel("Number");

        final LineChart<String, Number> lineChart = new LineChart<String, Number>(xAxis, yAxis);
        lineChart.setTitle("Line Chart");

        XYChart.Series<String, Number> series1 = new Series<String, Number>();
        series1.setName("Series");

        /** xAxis & yAxis Data */
        LinkedHashMap<String, Number> map = new LinkedHashMap<>();      
        map.put("dog", 12);
        map.put("cat", 3);
        map.put("bear", 8);
        map.put("tiger", 20);

        for (Entry<String, Number> entry : map.entrySet()) {
            series1.getData().add(new XYChart.Data<String, Number>(entry.getKey(), entry.getValue()));
        }

        lineChart.getData().add(series1);

        Scene scene = new Scene(lineChart);
        stage.setScene(scene);
        stage.show();

        WritableImage snapShot = scene.snapshot(null);
        ImageIO.write(SwingFXUtils.fromFXImage(snapShot, null), "png", new File("test.png"));
    }
}

Frame is great but saved-image doesn't have all chart-data that it should have. I want to save Chart-Image completely, what's wrong? ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀

like image 969
user2023865 Avatar asked Jan 30 '13 04:01

user2023865


1 Answers

Turn off animation on your chart.

From the snapshot javadoc:

When taking a snapshot of a scene that is being animated, either explicitly by the application or implicitly (such as chart animation), the snapshot will be rendered based on the state of the scene graph at the moment the snapshot is taken and will not reflect any subsequent animation changes.

like image 121
jewelsea Avatar answered Oct 30 '22 00:10

jewelsea