Search code examples
scalainternationalizationfxmlscalafxfxmlloader

ScalaFX i18n with fxml not working


First the working code:

val root: BorderPane = new BorderPane(jfxf.FXMLLoader.load(getClass.getResource("/GUI/main.fxml")))

stage = new PrimaryStage()
{
  title = "FXML Test"
  scene = new Scene(root)
}

No problem here. Now I wanted to add i18n support like so:

val bundle: ResourceBundle = new PropertyResourceBundle(getClass.getResource("/i18n/en.properties").openStream)
val loader: FXMLLoader = new FXMLLoader(getClass.getResource("/GUI/main.fxml"), bundle)
val root = loader.load[jfxs.Parent]

stage = new PrimaryStage()
{
  title = "FXML Test"
  scene = new Scene(root)
}

Now the constructor scene = new Scene(root) cannot be resolved.

I tried to solve this by

1) initializing a new BorderPane, like:

val root = new BorderPane(loader.load[jfxs.Parent])

But the constructor of BorderPane cannot be resolved so I tried

2) casting it to a BorderPane, like:

val root = new BorderPane(loader.load[jfxs.Parent].asInstanceOf[BorderPane])

which is okay in the IDE but throws a compiler-error:

Caused by: java.lang.ClassCastException: javafx.scene.layout.BorderPane cannot be cast to scalafx.scene.layout.BorderPane

How can I resolve this?


Solution

  • "Now the constructor scene = new Scene(root) cannot be resolved.": that would be because the scalafx.scene.Scene constructor expects a parameter of type scalafx.scene.Parent and not javafx.scene.Parent.

    Just add import scalafx.Includes._ to your imports to use ScalaFX's implicit conversions. You can then do:

    import java.util.PropertyResourceBundle
    import javafx.fxml.FXMLLoader
    import javafx.{scene => jfxs}
    
    import scalafx.Includes._
    import scalafx.application.JFXApp
    import scalafx.application.JFXApp.PrimaryStage
    import scalafx.scene.Scene
    
    object MyApp extends JFXApp{
      val bundle = new PropertyResourceBundle(getClass.getResource("/i18n/en.properties").openStream)
      val fxml = getClass.getResource("/GUI/main.fxml")
      val root: jfxs.Parent = FXMLLoader.load(fxml, bundle)
    
      stage = new PrimaryStage() {
        title = "FXML Test"
        scene = new Scene(root) // root is implicitly converted to scalafx.scene.Parent
      }
    }