【问题标题】:how to access stage object out of start method如何在启动方法之外访问舞台对象
【发布时间】:2015-12-16 08:53:09
【问题描述】:
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() 访问对象时遇到问题。我想在 keyPressedHandler() 中访问它...我是 javafx 的新手,帮助我找出我的错误...谢谢

【问题讨论】:

  • 您是否使用您的Application 子类作为您的控制器?如果是这样,请不要。
  • 不,我有不同的控制器...
  • 你能说明你是怎么打电话给keyPressedHandler()的吗?并发布堆栈跟踪。

标签: javafx fxml stage


【解决方案1】:

你的问题不是如何在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);
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 2014-01-15
    相关资源
    最近更新 更多