2016-09-28 56 views
8

我只想從JavaFX圖表API生成圖表圖像。我不想顯示應用程序窗口,或啓動應用程序(如果沒有必要)。使用JavaFX圖表API繪製圖表圖形

public class LineChartSample extends Application { 
    private List<Integer> data; 

    @Override public void start(Stage stage) { 
     stage.setTitle("Line Chart Sample"); 
     final CategoryAxis xAxis = new CategoryAxis(); 
     final NumberAxis yAxis = new NumberAxis(); 
     xAxis.setLabel("Month");  

     final LineChart<String,Number> lineChart = 
       new LineChart<String,Number>(xAxis,yAxis); 

     lineChart.setTitle("Stock Monitoring, 2010"); 

     XYChart.Series series = new XYChart.Series(); 
     series.setName("My portfolio"); 

     series.getData().add(new XYChart.Data("Jan", 23)); 
     series.getData().add(new XYChart.Data("Feb", 14));   

     Scene scene = new Scene(lineChart,800,600); 
     lineChart.getData().add(series); 

     WritableImage image = scene.snapshot(null); 
     ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", chartFile); 

     //stage.setScene(scene); 
     //stage.show(); 
    } 

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

    public setData(List<Integer> data) {this.data = data;} 
} 

裏面的啓動方法,我真的需要,以建立一系列的數據來訪問外部的數據,但似乎沒有辦法從啓動方法來訪問外部的數據,如果我的數據存儲在成員變量中data,當啓動被調用時它是空的。我其實不關心舞臺和場景對象,只要圖表圖像可以渲染,我應該如何解決問題?我想構建一個可以用輸入數據調用的API,並用數據繪製圖表,然後返回文件。

public File toLineChart(List<Integer> data) { 
... 
} 
+0

我想你想要做的是首先:用掃描儀從文件中讀取數據並存儲到一個數組或一些其他數據類型。下一步:您應該將存儲的信息傳遞給toLineChart方法。 toLineChart方法應該使用下面列出的一些想法來打印圖表。最重要的問題是如何存儲數據?它是在文本文件還是數據庫中? – Sedrick

回答

6

你並不需要出示StageNode必須連接到一個Scene。從doc of snapshot

注意:爲了讓CSS和佈局正常工作,節點必須 是場景的一部分(場景可以連接到一個階段,但不必 定)。

一個限制修改Scene是,它必須發生在J AVAFX應用程序線程,其中有先決條件的的JavaFX工具包必須初始化。

初始化可以通過擴展Application類,其中launch方法會爲你做它來完成,或者作爲一種解決方法,您可以創建在Swing事件調度線程進行JFXPanel實例。

如果要擴展Application,你在start方法執行一些代碼,可以確保該代碼將在的JavaFX應用程序線程執行,否則,你可以使用Platform.runLater(...)塊從不同的線程調用,以確保一樣。

這裏是一個可能的示例:

類提供一個靜態方法來繪製圖表到一個文件,並返回Filenull如果創建成功與否。

在該方法中JavaFX的工具包通過在搖擺EDT則圖表創建完成JavaFX的應用程序線程創建JFXPanel初始化。該方法使用兩個布爾值來存儲操作完成併成功。

該方法將不會返回,直到完成標誌切換爲真。

注意:這一個只是一個(工作)的例子,可以提高很多。

public class JavaFXPlotter { 

    public static File toLineChart(String title, String seriesName, List<Integer> times, List<Integer> data) { 

     File chartFile = new File("D:\\charttest.png"); 

     // results: {completed, successful} 
     Boolean[] results = new Boolean[] { false, false }; 

     SwingUtilities.invokeLater(() -> { 

      // Initialize FX Toolkit 
      new JFXPanel(); 

      Platform.runLater(() -> { 
       final NumberAxis xAxis = new NumberAxis(); 
       final NumberAxis yAxis = new NumberAxis(); 

       final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis); 

       lineChart.setTitle(title); 

       XYChart.Series<Number, Number> series = new XYChart.Series<>(); 
       series.setName(seriesName); 

       for (int i = 0; i < times.size(); i++) 
        series.getData().add(new XYChart.Data<Number, Number>(times.get(i), data.get(i))); 

       lineChart.getData().add(series); 

       Scene scene = new Scene(lineChart, 800, 600); 

       WritableImage image = scene.snapshot(null); 

       try { 
        ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", chartFile); 
        results[1] = true; 
       } catch (Exception e) { 
        results[0] = true; 
       } finally { 
        results[0] = true; 
       } 
      }); 
     }); 

     while (!results[0]) { 
      try { 
       Thread.sleep(500); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
     return (results[1]) ? chartFile : null; 
    } 


} 

和一個可能的使用

List<Integer> times = Arrays.asList(new Integer[] { 0, 1, 2, 3, 4, 5 }); 
List<Integer> data = Arrays.asList(new Integer[] { 4, 1, 5, 3, 0, 7 }); 

File lineChart = JavaFXPlotter.toLineChart("Sample", "Some sample data", times, data); 

if (lineChart != null) 
    System.out.println("Image generation is done! Path: " + lineChart.getAbsolutePath()); 
else 
    System.out.println("File creation failed!"); 

System.exit(0); 

並將所生成的圖象(charttest.png)

enter image description here

1

來自命令行:

import java.io.File; 
import java.io.IOException; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javafx.application.Application; 
import javafx.collections.FXCollections; 
import javafx.collections.ObservableList; 
import javafx.embed.swing.SwingFXUtils; 
import javafx.scene.Scene; 
import javafx.stage.Stage; 
import javafx.scene.chart.*; 
import javafx.scene.Group; 
import javafx.scene.image.WritableImage; 
import javax.imageio.ImageIO; 

public class PieChartSample extends Application { 

    private static String[] arguments; 

    @Override public void start(Stage stage) { 
     Scene scene = new Scene(new Group()); 
     stage.setTitle("Imported Fruits"); 
     stage.setWidth(500); 
     stage.setHeight(500); 

     ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList(); 

//    
     final PieChart chart = new PieChart(pieChartData); 
     chart.setTitle("Imported Fruits"); 
     for(int i = 0; i < arguments.length; i+=2) 
     { 
      System.out.println(arguments[i] + " " + arguments[i+1]); 
      chart.getData().add(new PieChart.Data(arguments[i], Double.parseDouble(arguments[i+1]))); 
     } 

     ((Group) scene.getRoot()).getChildren().add(chart); 

     saveAsPng(scene); 
     System.out.println("Done!"); 
     System.exit(0); 
     //stage.setScene(scene); 
     //stage.show(); 
    } 

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

    static void saveAsPng(Scene scene){ 
     try 
     { 
      WritableImage image = scene.snapshot(null); 

      File file = new File("tempPieChart.png"); 

      ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file); 
     } 
     catch (IOException ex) 
     { 
      Logger.getLogger(PieChartSample.class.getName()).log(Level.SEVERE, null, ex); 
     } 

    } 
} 

下一頁:清理並構建您的程序。 然後:找到你的jar文件在你的文件夾DIST後 是:瀏覽你的命令提示符下dist文件夾你的罐子是 然後運行:Java的罐子PieChartSample.jar香蕉14橙20葡萄15

enter image description here

結果:在同一文件夾作爲PieChartSample.jar文件

enter image description here