1

这是一个例子:

/*
 * Copyright 2013 ScalaFX Project
 * All right reserved.
 */
package scalafx.ensemble.example.charts

import scalafx.application.JFXApp
import scalafx.scene.Scene
import scalafx.collections.ObservableBuffer
import scalafx.scene.chart.LineChart
import scalafx.scene.chart.NumberAxis
import scalafx.scene.chart.XYChart

/** A chart in which lines connect a series of data points. Useful for viewing
  * data trends over time.
  *
  * @see scalafx.scene.chart.LineChart
  * @see scalafx.scene.chart.Chart
  * @see scalafx.scene.chart.Axis
  * @see scalafx.scene.chart.NumberAxis
  * @related charts/AreaChart
  * @related charts/ScatterChart
  */
object BasicLineChart extends JFXApp {

  stage = new JFXApp.PrimaryStage {
    title = "Line Chart Example"
    scene = new Scene {
      root = {

        val xAxis = NumberAxis("Values for X-Axis", 0, 3, 1)
        val yAxis = NumberAxis("Values for Y-Axis", 0, 3, 1)

        // Helper function to convert a tuple to `XYChart.Data`
        val toChartData = (xy: (Double, Double)) => XYChart.Data[Number, Number](xy._1, xy._2)

        val series1 = new XYChart.Series[Number, Number] {
          name = "Series 1"
          data = Seq(
            (0.0, 1.0),
            (1.2, 1.4),
            (2.2, 1.9),
            (2.7, 2.3),
            (2.9, 0.5)).map(toChartData)
        }

        val series2 = new XYChart.Series[Number, Number] {
          name = "Series 2"
          data = Seq(
            (0.0, 1.6),
            (0.8, 0.4),
            (1.4, 2.9),
            (2.1, 1.3),
            (2.6, 0.9)).map(toChartData)
        }

        new LineChart[Number, Number](xAxis, yAxis, ObservableBuffer(series1, series2))
      }
    }
  }
}

object Main {
  BasicLineChart.main(Array(""))
}

我将线发送BasicLineChart.main(Array(""))到控制台,出现一个 JavaFx 窗口,其中有一个折线图,控制台被阻止。当我关闭图表窗口时,我恢复了对 scala 控制台的访问。当我尝试再次启动同一个窗口时,出现错误:

scala>   BasicLineChart.main(Array(""))
java.lang.IllegalStateException: Application launch must not be called more than once
  at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:162)
  at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:143)
  at javafx.application.Application.launch(Application.java:191)
  at scalafx.application.JFXApp$class.main(JFXApp.scala:242)
  at BasicLineChart$.main(<console>:23)
  ... 35 elided

所以我有两个问题:

  1. 如何在控制台中启动 JavaFx 应用程序而不阻塞?

  2. 如何避免上述错误?


更新 1

根据 freenode 的一些建议,我将 BasicLineChart 更改为一个类并执行此操作:

object Main {
  val x = new BasicLineChart()
  x.main(Array(""))
  val y = new BasicLineChart()
  y.main(Array(""))
}

仍然得到同样的错误。

4

1 回答 1

4

在问题 2 上,快速浏览一下JFXApp,它调用了 javafx.application.Application.launch,此处的文档。该页面描述了生命周期,表明启动只能被调用一次。基本上 JFXApp 期望成为整个应用程序的入口点,因此不应多次调用。

如果您希望能够快速重新启动您的应用程序,我会考虑使用 run 或 runMain 从 SBT 运行它,而不是使用控制台。

关于问题 1,如果您决定从 SBT 运行,您应该能够在运行中进行分叉,SBT 文档中有详细信息,特别是尝试添加fork in run := truebuild.sbt.

于 2015-09-17T12:34:25.770 回答