如何在不实际显示窗口的情况下创建/保存 JavaFX 饼图的图像?
javafxobject oriented programmingprogramming更新于 2026/1/8 1:48:17
JavaFX 的 javafx.scene.chart 包提供了用于创建各种图表的类,即:折线图、面积图、条形图、饼图、气泡图、散点图等。
要创建这些图表中的任何一个,您需要 −
实例化相应的类。
设置所需的属性。
创建一个布局/组对象来保存图表。
将布局/组对象添加到场景。
通过调用 show() 方法显示场景。
这将在 JavaFX 上显示所需的图表窗口。
保存图像而不显示窗口
Scene 类的 snapshot() 方法拍摄当前场景的快照并将其作为 WritableImage 对象返回。
使用 SwingFXUtils 类的 FromFXImage() 方法,您可以从获得的 WritableImage 中获取 BufferedImage,并将其本地写入所需的 文件,如下所示 −
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "PNG", file);
示例
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.chart.PieChart;
import javafx.scene.image.WritableImage;
public class ChartsExample extends Application {
public void start(Stage stage) throws IOException {
//准备 ObservbleList 对象
ObservableList<PieChart.Data>pieChartData =
FXCollections.observableArrayList(
new PieChart.Data("Iphone 5S", 13),
new PieChart.Data("Samsung Grand", 25),
new PieChart.Data("MOTO G", 10),
new PieChart.Data("Nokia Lumia", 22));
//创建饼图
PieChart pieChart = new PieChart(pieChartData);
pieChart.setTitle("Mobile Sales");
pieChart.setClockwise(true);
pieChart.setLabelLineLength(50);
pieChart.setLabelsVisible(true);
pieChart.setStartAngle(180);
//创建 Group 对象
Scene scene = new Scene(new Group(), 595, 400);
stage.setTitle("图表示例");
((Group) scene.getRoot()).getChildren().add(pieChart);
//将场景保存为图像
WritableImage image = scene.snapshot(null);
File file = new File("D:\JavaFX\tempPieChart.png");
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "PNG", file);
System.out.println("Image Saved");
}
public static void main(String args[]){
launch(args);
}
}
输出
如果你观察输出路径,你可以找到保存的图像,如下所示−


