Getting started on Scala + JavaFX desktop application development

后端 未结 3 1329
天涯浪人
天涯浪人 2020-12-25 14:36

Is there some guide or walkthrough to building a Scala + JavaFX desktop application?

I\'m having hard time finding a good source and I am using IntelliJ IDEA as the

3条回答
  •  天涯浪人
    2020-12-25 14:57

    There are a few things to know when writing Scala based JavaFX applications.

    First, here's a sample hello world app:

    import javafx.application.Application
    import javafx.scene.Scene
    import javafx.scene.layout.StackPane
    import javafx.stage.Stage
    import javafx.scene.control.Label
    
    class Test extends Application {
      println("Test()")
    
      override def start(primaryStage: Stage) {
        primaryStage.setTitle("Sup!")
    
        val root = new StackPane
        root.getChildren.add(new Label("Hello world!"))
    
        primaryStage.setScene(new Scene(root, 300, 300))
        primaryStage.show()
      }
    }
    
    object Test {
      def main(args: Array[String]) {
        Application.launch(classOf[Test], args: _*)
      }
    }
    

    Running it you should get:

    enter image description here

    Here's an official hello world example in Java: http://docs.oracle.com/javafx/2/get_started/hello_world.htm

    The main differences are:

    • You have to write the so-called companion object with the def main() that launches the actual application.
    • You have to specify that it will be run in context of the class Test, and not the companion object: Application.launch(classOf[Test], args: _*).

    If you just try to run the application directly with Application.launch(args : _*) you will get this error:

    Exception in thread "main" java.lang.RuntimeException: Error: class Test$ is not a subclass of javafx.application.Application

    To learn more about JavaFX, just read the official documentation: http://docs.oracle.com/javafx/index.html

提交回复
热议问题