如何从 start 方法访问 stage 对象

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);
    }
}

我在从 start().

你的问题不是如何访问start()方法外的stage对象,而是如何正确调用keyPressedHandler()。确保控制器中对它的引用不为空。

没有 FXML 文件及其控制器,代码如下所示并且可以运行。

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);
}

}