我想创建图表并将结果图像发送给客户。 对于这种用例,我有一些简单的服务,该服务实现Application类并具有公共方法来返回结果文件名。
3个问题:
没有stage.show()并按关闭按钮的应用程序将等待一些操作。
我无法获得结果文件名。当从Appication类调用启动静态函数时,它将创建新的实例。结果总是空字符串。
在调试期间,我可以查看临时文件名。当我打开它时,我会看到空图。
import javafx.application.Application
import javafx.embed.swing.SwingFXUtils
import javafx.scene.Scene
import javafx.scene.chart.CategoryAxis
import javafx.scene.chart.LineChart
import javafx.scene.chart.NumberAxis
import javafx.scene.chart.XYChart
import javafx.scene.image.WritableImage
import javafx.stage.Stage
import java.nio.file.Files
import javax.imageio.ImageIO
import kotlin.random.Random
fun main(args: Array<String>) {
val someService = ChartService()
println("Send image file name: ${someService.getImage()}")
}
class ChartService : Application() {
private var measurements = List(10) { Random.nextInt(0, 50) }
private var resultFileName: String = ""
fun getImage(): String {
launch(this.javaClass)
return resultFileName
}
override fun start(stage: Stage) {
val xAxis = CategoryAxis()
val yAxis = NumberAxis()
xAxis.label = "Time"
//creating the chart
val mayChart = LineChart<String, Number>(xAxis, yAxis)
mayChart.title = "Chart"
val aXSeries = XYChart.Series<String, Number>()
aXSeries.name = "Legend"
measurements.forEachIndexed { index: Int, data: Int ->
aXSeries.data.add(XYChart.Data<String, Number>("$index", data))
}
val scene = Scene(mayChart, 800.0, 600.0)
mayChart.data.addAll(aXSeries)
stage.scene = scene
stage.show()
val image: WritableImage = scene.snapshot(null)
val file = Files.createTempFile("", "")
try {
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file.toFile())
} catch (ex: Exception) {
}
resultFileName = file.toString()
}
}