在创建构造函数时Application构造函数中的异常

时间:2018-04-29 10:02:35

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

但是如果我试图添加构造函数,它会在Application构造函数中获取Exception,Error。 代码是

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

我该如何解决这个问题?我需要传递String来收集上一课的信息。

2 个答案:

答案 0 :(得分:1)

Application.launch始终使用public无参数构造函数来创建要启动的应用程序类的实例。 (它在主要方法BTW中创建实例没有任何好处。只需在不创建实例的情况下传递类,即Application.launch(Test.class, args);。)

实际上,您只能在不使用String成员的情况下将static个参数传递到应用程序类的新实例,而是通过args的{​​{1}}参数完成:< / p>

Application.launch
public class Client {
    public static void main(String[] args) {
        Application.launch(Test.class, "Pass this String to Constructor");
    }
}

请注意,start方法也可以访问public class Test extends Application { String str; @Override public init() { this.str = getParameters().getRaw().get(0); } @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(); } } 属性。

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

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); } }); 方法。此外,参数未分配。

答案 1 :(得分:0)

AFAIK,Application.launch创建Test的新实例。因此,您需要另一种方法来获取实例的值,例如: G。在Client类中使用静态getter方法,该方法是从Test

调用的
相关问题