Reputation: 75
I am designing a JavaFX application and I need to call the Application class of one of the windows in the Controller of another window.
MainController.java:
public class MainController {
@FXML
public Button buttonLogin;
@FXML
public Button buttonNeuAnmelden;
@FXML
public void handleButtonLoginAction(ActionEvent event) {
((Node) (event.getSource())).getScene().getWindow().hide();
System.out.println("LoginButton geclickt!");
}
@FXML
public void handleButtonNeuAnmeldenAction(ActionEvent event) {
((Node) (event.getSource())).getScene().getWindow().hide();
System.out.println("NeuAnmeldenButton Geclickt!");
}
}
LoginApp.java:
public class LoginApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(
getClass().getResource("/design/Login.fxml"));
Parent root = loader.load();
primaryStage.setTitle("Benutzerverwaltung");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
I specifically need to run all of the methods of LoginApp
, meaning main(String[] args)
and start(Stage primaryStage)
class in handleButtonLoginAction()
method as if the whole class as it is has been called exactly at that point.
How do I do this?
Upvotes: 1
Views: 1535
Reputation: 209330
If I understand the question correctly, you need to refactor this quite a bit. Define a LoginView
class that is independent of your Application
subclass:
public class LoginView {
private final Stage displayStage ;
private final Scene scene ;
public LoginView(Stage displayStage) throws IOException {
this.displayStage = displayStage ;
FXMLLoader loader = new FXMLLoader(
getClass().getResource("/design/Login.fxml"));
Parent root = loader.load();
scene = new Scene(root);
displayStage.setScene(scene);
displayStage.setTitle("Benutzerverwaltung");
}
public LoginView() throws IOException {
this(new Stage());
}
public void show() {
displayStage.show();
}
public void hide() {
displayStage.hide();
}
// ...
}
and then your Application
class looks like:
public class LoginApp extends Application {
@Override
public void start(Stage primaryStage) throws IOException {
LoginView loginView = new LoginView(primaryStage);
// ...
loginView.show();
}
}
Your question didn't show how MainController
is related to the application, but all you need to do is pass a reference to the loginView
you created to the MainController
, and then call loginView.show()
from the method in the MainController
.
Upvotes: 2