科特林.基本的JavaFX应用程序 [英] Kotlin. Basic JavaFX application

查看:39
本文介绍了科特林.基本的JavaFX应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试Kotlin lang时,我印象中它与Java兼容,因此与JavaFX兼容,我尝试了以下操作:

Trying out Kotlin lang and I had an impression that it is compatible with Java and therefore with JavaFX and i tried following:

public object TestKt: Application() {

    public override fun start(stage: Stage){
        val pane= Pane()
        val scene=Scene(pane,200.0,200.0)
        stage.scene = scene
        stage.show()

    }
    @JvmStatic public fun main(args: Array<String>){
        launch()
    }
}

这基本上与Java相同

this is basically same as Java's

public class Test extends Application {
    @Override
    public void start(Stage stage)  {
        Pane pane=new Pane();
        Scene scene=new Scene(pane, 200,200);
        stage.setScene(scene);
        stage.show();
    }
    public static  void  main(String[] args){
        launch();
    }
}

但是Kotlin给出了一个错误:线程"main"中的异常java.lang.RuntimeException:无法构造应用程序实例:类Test

but Kotlin gives an error: Exception in thread "main" java.lang.RuntimeException: Unable to construct Application instance: class Test

推荐答案

您提供的代码示例不相同:

The code samples you provided are not equivalent: an object declaration in Kotlin is a singleton, so it only has one instance constructed by calling the private constructor when the class is initialized. JavaFX is trying to call the constructor of the class reflectively but fails because the constructor is private as it should be.

您可能正在寻找的是一个简单的类声明,其

What you may be looking instead is a simple class declaration, with the main in its companion object. If no explicit constructors are declared, Kotlin, like Java, will generate a default one, allowing JavaFX to instantiate the application:

class Test : Application() {
    override fun start(stage: Stage) {
        ...
    }

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            launch(Test::class.java)
        }
    }
}

这篇关于科特林.基本的JavaFX应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆