Search code examples
javafxfxmlstage

how to access stage object out of start method


public class grandParent extends Application {
    public Stage primaryStageClone = null;
    @Override
    public void start(Stage primaryStage) throws Exception{
        primaryStageClone = primaryStage;
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("searchBar.fxml"));
        final Parent root = (Parent) fxmlLoader.load();
        primaryStageClone.initStyle(StageStyle.TRANSPARENT);
        Scene scene = new Scene(root);
        scene.setFill(Color.TRANSPARENT);
        primaryStageClone.setScene(scene);
        primaryStageClone.setHeight(600);
        primaryStageClone.show();
//primaryStageClone working here....
    }

    public void keyPressedHandler() {
        System.out.println("Now in keyPressedHandler()");
        try{
            primaryStageClone.setHeight(600);//Unable to access here ....It gives exceptions...
        }catch(Exception e){
            primaryStageClone.setHeight(600);
        }

    }

    public static void main(String[] args) {
    // write your code here

        launch(args);
    }
}

I have the problem to access the object out of the start().. I want to access it in keyPressedHandler()... i'm new in javafx help me to figure out my mistake ... thanks


Solution

  • Your problem is not how to access the stage object outside the start() method, but how to call keyPressedHandler() correctly. Make sure that the reference to it in the controller is not null.

    Without the FXML file and its controller, the code looks like shown below and works.

    public class GrandParent extends Application {
    
    public Stage primaryStageClone = null;
    
    @Override
    public void start(Stage primaryStage) throws Exception{
        primaryStageClone = primaryStage;
        AnchorPane root = new AnchorPane();
    
         Button b = new Button();
         b.setText("Resize Stage");
         root.getChildren().add(b);
         b.setOnAction(new EventHandler<ActionEvent>() {
            @Override public void handle(ActionEvent e) {
                keyPressedHandler();
            }
        });
    
        Scene scene = new Scene(root, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    
    }
    
    public void keyPressedHandler() {
        System.out.println("Now in keyPressedHandler()");
        primaryStageClone.setHeight(200);
    }
    
    public static void main(String[] args) {
    // write your code here
    
        launch(args);
    }
    

    }