最近我在使用JavaFX时遇到了问题。我想要做的是让我的图形显示在场景中,并在单击按钮后将其导出为PNG文件。问题是,当我将它们导出到文件时,它们会从场景中消失(虽然导出的图像是可以的)。以下是我正在使用的代码部分:
@FXML
private PieChart pieChart;
(...)
ObservableList<PieChart.Data> pieChartData = FXCollections
.observableArrayList(new PieChart.Data("a",
13), new PieChart.Data("b", 10),
new PieChart.Data("c", 5),
new PieChart.Data("d", 22),
new PieChart.Data("e", 30),
new PieChart.Data("f", 5),
new PieChart.Data("g", 15));
pieChart.setData(pieChartData);
pieChart.setAnimated(false);
@FXML
private void handleNewButtonClick(ActionEvent event)
{
Charts.savePieChartToFile(pieChart.getData(), "diagram_file.png");
}
(...)
public static void savePieChartToFile(
ObservableList<PieChart.Data> pieChartData, String path)
{
PieChart pieChart = new PieChart(pieChartData);
Scene sceneForChart = new Scene(pieChart, 800, 600);
WritableImage image = pieChart.snapshot(new SnapshotParameters(), null);
File file = new File(path);
try
{
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
} catch (IOException e)
{
e.printStackTrace();
}
}
以下是它的样子:
我会感谢你就此事提出一些建议。