Java不需要使用Javafx的Application也能将Node导出图片

Java不需要使用Javafx的Application也能将Node导出图片

一、Java通用导出Javafx Chart图片

Javafx不需要使用Application也能导出图片,使用PlatformImpl.startup方法初始化Javafx的Toolkit。

Javafx API并不是所有机器都支持的,Node导出图片不一定成功。(如:无法初始化Javafx的Toolkit或者安装了Server JRE,则没有办法导出图片)。

二、Chart导出图片实例

www.zeeklog.com  - Java不需要使用Javafx的Application也能将Node导出图片

import com.sun.javafx.application.PlatformImpl;
import java.io.File;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.image.WritableImage;
import javax.imageio.ImageIO;

public class LineChartTest {

    public static void export() {

        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setLabel("Number of Month");
        //creating the chart
        final LineChart<Number, Number> lineChart
                = new LineChart<>(xAxis, yAxis);

        lineChart.setTitle("Stock Monitoring, 2010");
        //defining a series
        XYChart.Series series = new XYChart.Series();
        series.setName("My portfolio");
        //populating the series with data
        series.getData().add(new XYChart.Data(1, 23));
        series.getData().add(new XYChart.Data(2, 14));
        series.getData().add(new XYChart.Data(3, 15));
        series.getData().add(new XYChart.Data(4, 24));
        series.getData().add(new XYChart.Data(5, 34));
        series.getData().add(new XYChart.Data(6, 36));
        series.getData().add(new XYChart.Data(7, 22));
        series.getData().add(new XYChart.Data(8, 45));
        series.getData().add(new XYChart.Data(9, 43));
        series.getData().add(new XYChart.Data(10, 17));
        series.getData().add(new XYChart.Data(11, 29));
        series.getData().add(new XYChart.Data(12, 25));
        lineChart.getData().add(series);
        //防止坐标刻度不显示
        lineChart.setAnimated(false);
        //必须添加到场景,否则图表不绘制
        Scene scene = new Scene(lineChart, 800, 600);
        WritableImage writableImage = new WritableImage(800, (int) 600);
        lineChart.snapshot(new SnapshotParameters(), writableImage);

        File fileA = new File("./chart.png");
        try {
            ImageIO.write(SwingFXUtils.fromFXImage(writableImage, null), "png", fileA);
        } catch (Exception s) {
            s.printStackTrace();
        }

    }

    public static void main(String[] args) throws InterruptedException {

        PlatformImpl.startup(() -> {
            export();
            System.err.println("finish");
            System.exit(0);//退出程序
        });

    }
}