1 Reply Latest reply: Mar 5, 2013 7:25 AM by James_D RSS

    SavePie chart as image in JavaFX

      I wish to save the chart I generate as an Image My Piecode is as follows :

      PieChart createChart(String category,String year,String quarter) {
      // ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList();
      ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList();
      PieChart pc;
      //ObservableList data;

      //data = FXCollections.observableArrayList();

      try {
      Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "password");//*BF06A06D69EC935E85659FCDED1F6A80426ABD3B

      Statement stmt = null;
      int count = 0;

      // stmt=con.createStatement();

      case "q1":quarter=" and (month(dor)=01 or month(dor)=02 or month(dor)=03)) ";
      case "q2":quarter=" and (month(dor)=04 or month(dor)=05 or month(dor)=06)) ";
      case "q3":quarter=" and (month(dor)=07 or month(dor)=08 or month(dor)=09)) ";
      case "q4":quarter=" and (month(dor)=10 or month(dor)=11 or month(dor)=12)) ";
      else quarter=") ";

      String pie2 = "select COUNT(emp) as c,"+category+",dor from excel1 where (year(dor)="+year+quarter+"group by "+category;
      stmt = con.createStatement();

      ResultSet prs = stmt.executeQuery(pie2);

      while (prs.next()) {
      System.out.println(prs.getString(category) + "\t" + prs.getInt("c"));
      pieChartData.add(new PieChart.Data(prs.getString(category), prs.getDouble("c")));
      } catch (Exception e) {
      // PieChart chart1=new PieChart();
      pc = new PieChart();
      for (Node node : pc.lookupAll("Text.chart-pie-label")){
      if (node instanceof Text){
      for (PieChart.Data data : pieChartData){
      if (data.getName().equals(((Text) node).getText()))
      ((Text) node).setText(String.format("%,.0f", data.getPieValue()));
      pc.setTitle("Attrition for the year :"+ year+" Viweing "+category+"-wise");

      return pc;

      I searched online on how to save a chart and I found this:

      WritableImage snapShot = scene.snapshot(null);

      ImageIO.write(SwingFXUtils.fromFXImage(snapShot, null), "png", new File("Ananth/test.png"));

      But my "scene" is defined in another method . Is there some way i can do it ?
        • 1. Re: SavePie chart as image in JavaFX
          The Node class also defines a snapshot(...) method. So you can (for example) call it on the pie chart itself:
          PieChart pc = createChart(...) ;
          WritableImage image = pc.snapshot(null, null) ;
          ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", new File("Ananth/test.png"));