6

Main.class

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/application/Main.fxml"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

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

MainController.class

    public class MainController implements Initializable {

    @FXML private MediaView mv;
    private MediaPlayer mp;
    private Media me;

    @FXML Slider volumeSlider;

    DoubleProperty width;
    DoubleProperty height;

    Stage stage;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // TODO Auto-generated method stub
        String path = new File("src/media/my.mp4").getAbsolutePath();
        me = new Media(new File(path).toURI().toString());
        mp = new MediaPlayer(me);
        mv.setMediaPlayer(mp);
        //mp.setAutoPlay(true);

        stage = (Stage) mv.getScene().getWindow();  // Error occured

        width = mv.fitWidthProperty();
        height = mv.fitHeightProperty();
        width.bind(Bindings.selectDouble(mv.sceneProperty(), "width"));
        height.bind(Bindings.selectDouble(mv.sceneProperty(), "height"));

        volumeSlider.setValue(mp.getVolume() * 100);
        volumeSlider.valueProperty().addListener(new InvalidationListener() {

            @Override
            public void invalidated(Observable observable) {
                // TODO Auto-generated method stub
                mp.setVolume(volumeSlider.getValue() / 100);
            }
        });
    }

    public void play(ActionEvent event){
        mp.play();
        mp.setRate(1);
    }
    public void pause(ActionEvent event){
        mp.pause();
    }
    public void fast(ActionEvent event){
        mp.setRate(2);
    }
    public void slow(ActionEvent event){
        mp.setRate(.5);
    }
    public void reload(ActionEvent event){
        mp.seek(mp.getStartTime());
        mp.play();
    }
    public void start(ActionEvent event){
        mp.seek(mp.getStartTime());
        mp.stop();
    }
    public void last(ActionEvent event){
        mp.seek(mp.getTotalDuration());
        mp.stop();
    }
    public void fullScreen(ActionEvent event){

    }
}

Error

javafx.fxml.LoadException: 
/C:/Users/SOONMYUN/workspace/MediaPlayer/bin/application/Main.fxml

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at application.Main.start(Main.java:17)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at application.MainController.initialize(MainController.java:44)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
    ... 17 more

I want to get the Stage from Main class to Controller class but it was failed.

Because I should use the setFullScreen function in Controller class.

1615903
  • 32,635
  • 12
  • 70
  • 99
Soonmyun Jang
  • 300
  • 5
  • 12

2 Answers2

15

i am answering how to pass stage object from main class to your controller class create a function in your controller class

public void setStage(Stage stage){
this.stage=stage;
}

now call this function in your main class like this

 FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/application/Main.fxml"));
                Parent root = (Parent) fxmlLoader.load();
  ((MainController) fxmlLoader.getController()).setStage(primaryStage);

if you want to get the stage object without passing it from main to class to controller class you can do this way

1.Give id to your AnchorPane e.g. fx:id="ap" then in your Controller class

@FXML
AnchorPane ap;

2.where you want the object

Stage stage = (Stage) ap.getScene.getWindow();
Sahil Manchanda
  • 9,812
  • 4
  • 39
  • 89
  • Thanks a lot!! It's working – Soonmyun Jang Oct 28 '16 at 06:55
  • Glad it helped. please upvote and accept the answer – Sahil Manchanda Oct 28 '16 at 06:56
  • I'm sorry I couldn't upvote because I have not enough Reputation.. – Soonmyun Jang Oct 28 '16 at 07:11
  • @SoonmyunJang no need to sorry buddy. happy coding – Sahil Manchanda Oct 28 '16 at 07:20
  • Hi. The setStage function successfully runs, but when I try to use stage in my controller class, `stage.sizeToScene()` gives me a nullpointerexception. I use `stage.sizeToScene()` in a separate function `authenticate(ActionEvent event)` in the same controller class. Would I need to pass `stage` into this `authenticate(ActionEvent event)` function? Thanks. – Riley Fitzpatrick Jan 27 '19 at 20:26
  • @RileyFitzpatrick NullPointerException means it's not initialized when you are trying to use it. make sure you've called setStage like in the answer. if it still giving you the exception you can use any of your UI element like button to access stage object. just like other way specified in the answer. let me know if you need help. – Sahil Manchanda Jan 28 '19 at 05:01
  • Thanks! I was actually able to fix this by creating a `new Runnable()` inside my `initialize()`. – Riley Fitzpatrick Jan 28 '19 at 21:41
  • 7 days of searching finally got a stage in the controller. but why we can't declare it as a private global variable in the FXMLDocumentController file? as local variable, it works fine – Shiva_Adasule Mar 23 '20 at 18:48
2

To access stage from controller:

  • Create a setter method for stage variable in your Controller class
  • Get instance of the controller in your Main.java class

  • Set the stage variable of controller through setter method in Main.java

    Illustration:

    Step 1 :

        public class MainCOntroller {
    
         private Stage primaryStage;
    
            public void setPrimaryStage(Stage primaryStage){
                       this.primaryStage = primaryStage;
             }
                .....
               .....      
         }       
    

    Step 2 and 3: get the instance of controller and set the stage using setter method

      public class Main extends Application {
      @Override
      public void start(Stage primaryStage) {
        try {
          FXMLLoader loader = new FXMLLoader(getClass().getResource("/application/Main.fxml"));
         Parent root = (Parent)loader.load();
    
         MainController controller = (MainController) loader.getController(); 
    
          //set stage 
           controller.setPrimaryStage(primaryStage);
      } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
MR.JOIS
  • 77
  • 1
  • 9