且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

开始使用Scala + JavaFX桌面应用程序开发

更新时间:2023-02-16 15:26:06

编写基于Scala的JavaFX应用程序时需要了解一些事项。

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: _*)
  }
}

运行它你应该得到:

以下是Java中的官方hello world示例: http://docs.oracle.com/javafx/2/get_started/hello_world.htm

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

主要区别在于:


  • 您必须使用 def main()编写所谓的伴随对象,以启动实际的应用程序。

  • 您必须指定它将在Test类的上下文中运行,而不是在伴侣对象中运行: Application.launch(classOf [Test],args: _ *)

  • 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: _*).

如果您只是尝试使用直接运行应用程序Application.launch(args:_ *)你会收到这个错误:

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


线程main中的异常java.lang.Runt imeException:错误:class
Test $不是
的子类javafx.application.Application

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

要学习有关JavaFX的更多信息,请阅读官方文档: http://docs.oracle.com/javafx/index .html

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