【问题标题】:Using standalone methods for each scene in JavaFX在 JavaFX 中为每个场景使用独立方法
【发布时间】:2017-04-09 17:54:47
【问题描述】:

我正在尝试将我的场景 home 用作 start 中的场景。
但是它不起作用,我没有得到我的 300 x 300,而是得到一个空白的 900 x 400 屏幕。也许这是很容易检测到但我没有看到的东西?

    private Scene home;
    private Stage window;    

    public Scene home(Scene home) {
        // build my scene
        return home = new Scene(root, 300, 300);
    } 

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setScene(home);
        window.show();
    } 

我正在尝试将我的场景创建为方法,这样我就可以将它们排除在start之外。
计划稍后切换场景使用:btn.setOnAction(e -> window.setScene(anotherScene));,提前谢谢大家!

【问题讨论】:

    标签: java javafx methods scene stage


    【解决方案1】:

    你永远不会调用home 方法。因此,home 字段将保留为 null,这是您传递给 window.setScene 的值。

    此外,我会调用home 方法以一种奇怪的方式实现:

    public Scene home(Scene home) {
    

    参数永远不会被读取。

        return home = new Scene(root, 300, 300);
    

    这会将值分配给方法参数,而不是在返回场景之前分配给场景,这没有任何效果,因为java是按值调用的。

    你可以这样实现它:

    private Scene home;
    private Stage window;    
    
    public Scene home() {
        if (home == null) {
            // build my scene
            home = new Scene(root, 300, 300)
    
            // or maybe do this without testing, if the scene was created before???
        }
        return home;
    } 
    
    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setScene(home()); // use the method here
        window.show();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      • 2014-04-05
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      相关资源
      最近更新 更多