我想在javafx中声明一个折线图并截取屏幕截图。添加数据,数据系列和xAxis和yAxis后,它将传递给屏幕截图方法。尝试调用该方法时会发生此异常。
CategoryAxis monthAxis = new CategoryAxis();
monthAxis.setLabel("Month");
NumberAxis profitAxis = new NumberAxis();
profitAxis.setLabel("Profit");
String[] monthName = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
LineChart profitLineChart = new LineChart(monthAxis, profitAxis);
XYChart.Series series1 = new XYChart.Series();
int[] profitValues = new int[monthlyRecords.size()];
int[] monthNo = new int[monthlyRecords.size()];
for (int i = 0; i < monthlyRecords.size(); i++) {
profitValues[i] = Integer.parseInt(monthlyRecords.get(i).getProfit());
monthNo[i] = Integer.parseInt(monthlyRecords.get(i).getMonth());
series1.getData().add(new XYChart.Data(monthName[monthNo[i]-1], profitValues[i]));
}
profitLineChart.getData().addAll(series1);
saveProfitLineChartToFile(monthAxis,profitAxis,series1.getData(), "profitLineChart.png");
正在调用的方法:
public static void saveProfitLineChartToFile(CategoryAxis monthAxis, NumberAxis profitAxis,ObservableList<LineChart.Data> lineChartData, String path) throws IOException {
LineChart lineChart = new LineChart(monthAxis,profitAxis,lineChartData);
Scene sceneForChart = new Scene(lineChart, 800, 600);
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();
}
}
发生的异常:
javafx.scene.chart.XYChart$Data cannot be cast to javafx.scene.chart.XYChart$Series
答案 0 :(得分:1)
应该称为:
saveProfitLineChartToFile(monthAxis,profitAxis,profitLineChart.getData(), "profitLineChart.png");