0

I want to pop a new window up by clicking a button. since I am using scene builder, my project has main.java and controller.java. and i have two fxml files named Interface.fxml(which primarily appears) and Popup.fxml.

I searched a lot but all the questions and answers were about doing it in main.java not in controller.java. I read about referencing stage and scene in other class but I have failed in implementing.

Here is what i have wrote.

import ...
public class Main extends Application {
  @Override
  public void start(Stage primaryStage) {
    try {
      Parent root = FXMLLoader.load(getClass().getResource("Interface.fxml"));
      Scene scene = new Scene(root);
      primaryStage.setTitle("Calculator");
      primaryStage.setScene(scene);
      primaryStage.show();
    } catch(Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    launch(args);
  }
}

code above is main.java and

@FXML
private void onButtonClicked(ActionEvent ae) {
  try {
    FXMLLoader loader=new FXMLLoader(getClass().getResource("Popup.fxml"));
    loader.setRoot(this);
    loader.setController(this);

    loader.load();

  } catch(Exception e) {
    e.printStackTrace();
  }
}

Code above is in controller.java.

I want to know how to create a new window in a controller.java. Please help me out! (if additional part is needed, please let me know.)

Jino
  • 43
  • 6
  • BTW: You may want to use different controllers or at least different instances of the same controller class for the fxmls instead of reusing the same instance. Furthermore in most cases using the controller of a different fxml that is not supposed to be displayed in the same `Scene` as a the `root` would not be appropriate. I'm not saying there are no scenarios where this would be appropriate, but you should know what you're doing when you write `loader.setRoot(this); loader.setController(this);` in a method of a controller that is already in use with a fxml. – fabian Jan 08 '18 at 10:36
  • Thanks for your comment! I have suceeded in making a new window and called a file chooser in that window. Then I got a String type path of an image chosen from the file chooser. And now I have to pass this String to the Original window which has different controller. But now I am stucked returning this value to the original one. Can you help me out? (I have to pass variable from the new stage's controller to the original one's. ) – Jino Jan 09 '18 at 02:31
  • I figured it out ! thx! – Jino Jan 09 '18 at 04:14

0 Answers0