根据查询参数显示动态图表图像
如何正确使用JavaFX在Web服务(可能是Springboot应用程序)中生成图表图像?
我遵循http://www.greggbolinger.com/let-spring-be-your-javafx-controller-factory/,创建了一个自定义应用程序,该应用程序扩展了javafx.application.Application
@ResponseBody
@RequestMapping(value = "/photo2", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
public byte[] testphoto() throws IOException, InterruptedException {
String austria = "Austria";
String brazil = "Brazil";
String france = "France";
String italy = "Italy";
String usa = "USA";
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis();
StackedBarChart<String, Number> sbc =
new StackedBarChart<>(xAxis, yAxis);
XYChart.Series<String, Number> series1 =
new XYChart.Series<>();
XYChart.Series<String, Number> series2 =
new XYChart.Series<>();
XYChart.Series<String, Number> series3 =
new XYChart.Series<>();
//stage.setTitle("Bar Chart Sample");
sbc.setTitle("Country Summary");
xAxis.setLabel("Country");
xAxis.setCategories(FXCollections.<String>observableArrayList(
Arrays.asList(austria, brazil, france, italy, usa)));
yAxis.setLabel("Value");
series1.setName("2003");
series1.getData().add(new XYChart.Data<>(austria, 25601.34));
series1.getData().add(new XYChart.Data<>(brazil, 20148.82));
series1.getData().add(new XYChart.Data<>(france, 10000));
series1.getData().add(new XYChart.Data<>(italy, 35407.15));
series1.getData().add(new XYChart.Data<>(usa, 12000));
series2.setName("2004");
series2.getData().add(new XYChart.Data<>(austria, 57401.85));
series2.getData().add(new XYChart.Data<>(brazil, 41941.19));
series2.getData().add(new XYChart.Data<>(france, 45263.37));
series2.getData().add(new XYChart.Data<>(italy, 117320.16));
series2.getData().add(new XYChart.Data<>(usa, 14845.27));
series3.setName("2005");
series3.getData().add(new XYChart.Data<>(austria, 45000.65));
series3.getData().add(new XYChart.Data<>(brazil, 44835.76));
series3.getData().add(new XYChart.Data<>(france, 18722.18));
series3.getData().add(new XYChart.Data<>(italy, 17557.31));
series3.getData().add(new XYChart.Data<>(usa, 92633.68));
sbc.getData().addAll(series1, series2, series3);
Scene scene = new Scene(sbc, 800, 600);
final WritableImage[] snapshot = new WritableImage[1];
Platform.runLater(() -> {
/*
* This line throws a exception with the following message
* (if not inside Platform.runLater):
* "Not on FX application thread"
*/
snapshot[0] = scene.snapshot(null);
});
// This is bad code, how to work around it?
Thread.sleep(3000);
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(SwingFXUtils.fromFXImage(snapshot[0], null), "png", output);
return output.toByteArray();
}