Your problem is, that you use your Application
class as controller. That means the FXMLLoader
tries to create another instance of Main
. You have to create a different class for the controller.
Your modified Main class:
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
private Stage myStage;
public static void main(String[] args) {
Application.launch(Main.class, args);
}
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader();
// this creates a instance of Controller now
// and not a instance of Main
Parent root = (Parent) loader.load(getClass().getResourceAsStream("load.fxml"));
// get the controller corresponding to root
Controller controller = loader.getController();
// tell the controller that this is it's Main class
controller.setMain(this);
stage.setTitle("FXML Welcome");
stage.setScene(new Scene(root, 300, 275));
stage.show();
myStage = stage;
}
public void handleLoadButton() throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("main.fxml"));
myStage.setTitle("FXML Main");
myStage.setScene(new Scene(root, 300, 275));
myStage.show();
}
}
The controller class:
import java.io.IOException;
import javafx.fxml.FXML;
public class Controller {
@FXML
private void handleLoadButton() throws IOException {
myMain.handleLoadButton();
}
private Main myMain;
public void setMain(Main myMain) {
this.myMain = myMain;
}
}
Of course you have to replace the controller class in load.fxml
:
The fx:controller
attribute in the Root node of the file should be:
fx:controller="Controller"
you may have to add the package name, if you're not using the default package.