Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin. Basic JavaFX application

Tags:

kotlin

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()     } } 

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();     } } 

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

like image 554
Elavrius Avatar asked Jan 16 '16 23:01

Elavrius


People also ask

Can I use Kotlin with JavaFX?

Creating the Kotlin JavaFX projectIntelliJ IDEA is the editor of choice for a Kotlin project. This tutorial works with the community (free) edition of IDEA as well as the ultimate edition. Let's start by creating a new Kotlin project, and choose JVM Application. Choose the name and location of your project.

What is JavaFX application application?

A JavaFX application defines the user interface container by means of a stage and a scene. The JavaFX Stage class is the top-level JavaFX container. The JavaFX Scene class is the container for all content. Example 1-1 creates the stage and scene and makes the scene visible in a given pixel size.


2 Answers

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)         }     } } 
like image 111
Alexander Udalov Avatar answered Sep 30 '22 05:09

Alexander Udalov


class MyApplication : Application() {     override fun start(primaryStage: Stage) {     } }  fun main(args: Array<String>) {    Application.launch(MyApplication::class.java, *args) } 
like image 44
jenglert Avatar answered Sep 30 '22 05:09

jenglert