Issue
I have simple main class.
There i try pass user
to 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();
}
}
Window main class. There i try call test()
function of user
(in real, i need it pass to 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(); }
}
When i try to run it all:
Exception in Application start method
Of course (maybe :) ) it because of user
in windowLogin is null
.
What i doing wrong? How pass user
to windowLogin
? (i wont use Singletone)
Update:
I need use user
in start() method, as i said before - i need pass user
to WindowMainController
Solution
OverView
The problem you are facing here is on calling launch(), Javafx thread creates a new object of WindowLogin
. So the object that you have created for WindowLogin
and assigned user to it is no longer used in the start method !
WindowLogin windowLogin = new WindowLogin();
windowLogin.user = user;
You can overcome this by declaring the User
in WindowLogin as static !
public static User user;
This will help to just keep on instance of the User
Answered By - ItachiUchiha