0

I'm using JavaFX + FXML together with Scala to build a GUI but I get a NullPointerException in the Controller for all Controls from the FXML-file when I use a for-loop or a mapping (of a Scala Collection).

Info: I programmed the exact same example completely in Java and used a for-loop and it worked. It only fails with Scala.

I constructed a very simple FXML + Controller so you can reproduce the Failure (you need to out-comment one of the loops to test it).

Here's my simple FXML (example.fxml):

<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.GridPane?>


<GridPane fx:id="grid" prefHeight="289.0" prefWidth="473.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="application.Controller2">
</GridPane>

and here's the Controller2.scala:

package application
import javafx.fxml.FXML
import javafx.scene.layout.{ GridPane, ColumnConstraints }
import javafx.scene.shape.Rectangle;

class Controller2 {
  @FXML private var grid: GridPane = _

  @FXML def initialize = {
    println(grid)

    // doesn't work
    for (i <- 0 until 100) {
      grid.getColumnConstraints().add(new ColumnConstraints(100));
      grid.add(new Rectangle(10, 10), i, 0);
    }

    // works
    var i = 0
    while (i < 100) {
      grid.getColumnConstraints().add(new ColumnConstraints(100));
      grid.add(new Rectangle(10, 10), i, 0);
      i = i + 1
    }
  }
}

Any insight into this matter would be highly appreciated

  • I just saw this Thread http://stackoverflow.com/questions/31406700/scala-get-fxml-ui-elements and the for-loop does work, when I declare grid as public! –  Jun 30 '16 at 21:28
  • 2
    This is very probably the same issue I explained in [this question](http://stackoverflow.com/q/31754053/3801695): some name mangling done by the Scala compiler is colliding with the hideousness that is private field injection. You can check by looking at the bytecode with javap. You can also try making the field protected (rather than outright public), I think it will be enough to avoid the problem? Or try using scalafxml, which sensibly supports constructor injection (but it currently has some limitations though...). – Cyäegha Jun 30 '16 at 22:34
  • 1
    I have set the variables to protected and the Failure disappeared. Thank you –  Jul 01 '16 at 08:49

0 Answers0