Search code examples
scalascalafx

How to set up an linear chart in Scala FXML controller?


I am trying to build a ScalaFX application displaying a linear chart.

I have defined the line chart controller member as

@javafx.fxml.FXML
private val lineChart: XYChart = _

And am trying to add data with

val data = ObservableBuffer(Seq(
  (1, 23),
  (2, 14),
  (3, 15)
) map {case (x, y) => XYChart.Data[Number, Number](x, y).delegate} )

val series = XYChart.Series[Number, Number]("My series", data)
lineChart.data.set(series)

But I get 2 errors here:

First Idea highlights "series" (in lineChart.data.set(series)) and says "Type mismatch, expected: ObservableList[XYChart.Series[X, Y]], actual XYChart.Series[Number, Number]"

Second - when I try to build I get "unbound placeholder parameter private val lineChart: XYChart = _" error.

Any suggestions? ^


Solution

  • I have found the answers myself, let me share them for anybody who may be having the same problems.

    • Use var, not val

    • Use the LineChart type, not XYChart

    • Specify the chart axes types

    • Use javafx.scene.chart.LineChart, not scalafx.scene.chart.LineChart (would be nice if anybody could suggest the right way with ScalaFX though)

    Wrong:

    private val lineChart: XYChart = _
    

    Right:

    private var lineChart: LineChart[Number, Number] = _
    
    • Use lineChart.getData.add(series), not lineChart.data.set(series)

    • Set fx:controller to the controller full name in the FXML code (not added by Scene Designer)

    It works as expected then.