java将对象从主类传递到JavaFX应用程序
我有简单的主课。
在那里,我尝试将user
传递给WindowLogin
:
package client;
public class Client{
public User user;
public static void main(String[] args) {
try {
Client client = new Client();
client.run(args);
} catch (Exception e) {
System.out.println("[ERR] Fatal error");
}
}
public void run(String[] args)
{
user = new User();
WindowLogin windowLogin = new WindowLogin();
windowLogin.user = user;
windowLogin.show();
}
}
窗口主类。在那里,我尝试调用user
的test()
函数(实际上,我需要它传递给WindowMainController
):
package client;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.Parent;
import java.io.IOException;
public class WindowLogin extends Application{
private Stage stage;
public User user;
@Override
public void start(Stage primaryStage) throws Exception {
stage = new Stage();
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("views/WindowLogin.fxml"));
WindowLoginController controller =
fxmlLoader.<WindowLoginController>getController();
user.test();
Parent root = fxmlLoader.load();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void show(){
launch();
}
public void hide() { stage.hide(); }
}
当我尝试运行这一切时:
Exception in Application start method
当然(也许:)这是因为windowLogin中的user
是null
我做错了什么?如何将user
传递给windowLogin
?(我不会用单音)
更新:
我需要在start()方法中使用user
,正如我之前所说的——我需要将user
传递给WindowMainController
# 1 楼答案
概述
这里面临的问题是调用launch(),Javafx线程创建一个新的
WindowLogin
对象。因此,您为WindowLogin
创建并为其分配用户的对象不再用于start方法您可以通过将WindowLogin中的
User
声明为静态来克服这个问题这将有助于只保留用户的实例