Javafx 创建构造函数时应用程序构造函数中出现异常

Javafx 创建构造函数时应用程序构造函数中出现异常,javafx,Javafx,当我运行下面提到的代码时,它正在工作 import javafx.application.Application; public class Client { public static void main(String[] args){ Test t2 = new Test(); Application.launch(t2.getClass(),args); } } 测试类在哪里 package com.temp.com.serverclient; import j

当我运行下面提到的代码时,它正在工作

import javafx.application.Application;
public class Client {
public static void main(String[] args){
    Test t2 = new Test();
    Application.launch(t2.getClass(),args);
    }
}
测试类在哪里

package com.temp.com.serverclient;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Test extends Application {
@Override
public void start(Stage primaryStage) {
    primaryStage.setTitle("No Main");
    StackPane root = new StackPane();
    root.getChildren().add(new Label("It worked!"));
    primaryStage.setScene(new Scene(root, 300, 120));
    primaryStage.show();
    }
}
但若我试图添加构造函数,那个么它在应用程序构造函数中得到异常,错误。 代码是

package com.temp.com.serverclient;

import javafx.application.Application;

public class Client {
public static void main(String[] args){

    Test t1 = new Test("Pass this String to Constructor");
    Application.launch(t1.getClass(),args);
    }
}
测试班

package com.temp.com.serverclient;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Test extends Application {
String str;
public Test(String str) {
    this.str = str;
}
@Override
public void start(Stage primaryStage) {
    primaryStage.setTitle("No Main");
    StackPane root = new StackPane();
    root.getChildren().add(new Label("It worked!"));
    primaryStage.setScene(new Scene(root, 300, 120));
    primaryStage.show();
    }
 }

我怎样才能解决这个问题?我需要传递字符串以从上一节课收集信息

AFAIK,
Application.launch
创建
Test
的新实例。因此,您需要另一种方法来获取实例的值,例如。G在
客户端
类中使用从
测试

应用程序调用的静态getter方法。启动
始终使用
公共
无参数构造函数创建要启动的应用程序类的实例。(顺便说一句,在主方法中创建实例没有任何好处。只需传递类而不创建实例,即
Application.launch(Test.class,args);

事实上,您只能将
String
参数传递给应用程序类的新实例,而无需使用
静态
成员,这是通过
应用程序的
args
参数完成的。启动

public class Client {
    public static void main(String[] args) {
        Application.launch(Test.class, "Pass this String to Constructor");
    }
}
请注意,对于start方法,也可以访问
参数
属性


JavaFX9引入了一种新的可能性:使用
Platform.startup
,但您需要自己处理应用程序类的生命周期:

Application app = new Test("Pass this String to Constructor");
app.init();
Platform.startup(() -> {
    Stage stage = new Stage();
    try {
        app.start(stage);
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
});
这无法正确调用
应用程序。但请停止
方法。此外,未指定参数

Application app = new Test("Pass this String to Constructor");
app.init();
Platform.startup(() -> {
    Stage stage = new Stage();
    try {
        app.start(stage);
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
});