JavaFX启动内部Application类

时间:2017-08-28 14:10:11

标签: java javafx inner-classes

我正在尝试从封闭类中启动一个内部Application类,但这不起作用。

我已经尝试从Window中删除static修饰符并从Main实例启动它。

代码:

import javafx.application.Application;
import javafx.stage.Stage;

public class Main {
    private static class Window extends Application {
        @Override
        public void start(Stage stage) {
            stage.show();
        }
    }

    public static void main(String args[]) {
        Application.launch(Window.class, args);
    }
}

例外:

Exception in Application constructor
Exception in thread "main" java.lang.RuntimeException: Unable to construct Application instance: class VirtualLaunchpad$Window
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:907)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NoSuchMethodException: VirtualLaunchpad$Window.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getConstructor(Class.java:1825)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$7(LauncherImpl.java:818)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$5(GtkApplication.java:139)
    ... 1 more

1 个答案:

答案 0 :(得分:3)

Application子类(及其no-arg构造函数)必须是公共的。 Application.launch()方法仅在通过反射实例化应用程序类时才搜索公共的无参数构造函数。

import javafx.application.Application;
import javafx.stage.Stage;

public class Main {
    public static class Window extends Application {
        @Override
        public void start(Stage stage) {
            stage.show();
        }
    }

    public static void main(String args[]) {
        Application.launch(Window.class, args);
    }
}