【问题标题】:NullPointerException when I'm changing the scene in JAVAFX当我在 JAVAFX 中更改场景时出现 NullPointerException
【发布时间】:2016-03-25 21:04:16
【问题描述】:

当我按下 startgame 按钮和 exitgame 按钮时,我想更改舞台上的场景或关闭舞台,但它只显示第一个场景,当我试图按下其中一个按钮时,编译器关闭以防出现 NullPointerException .

我也有主类和两个fxml文件,不过我觉得没必要放在这里,它只包含两个锚窗格、原始标签和按钮。

package sample;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable{

    private Stage stage = new Stage();

    private FXMLLoader loader = new FXMLLoader();

    private AnchorPane anchorPane = new AnchorPane();

    private Scene scene = new Scene(new AnchorPane());

    @FXML private Button startGameButton;
    @FXML private Button endGameButton;

    @FXML private Button buttonAnswer1;
    @FXML private Button buttonAnswer2;
    @FXML private Button buttonAnswer3;
    @FXML private Button buttonAnswer4;

    public void createScene(int typeOfScene) throws Exception
    {
        if (typeOfScene == 1)
        {
            loader = new FXMLLoader(getClass().getResource("/sample/sample.fxml"));
            anchorPane = loader.load();

            scene = new Scene(anchorPane);
            stage.setScene(scene);
            stage.show();
        }

        if (typeOfScene == 2)
        {
            scene = null;

            loader = new FXMLLoader(getClass().getResource("/sample/episodesFXML.fxml"));

            anchorPane = loader.load();

            scene = new Scene(anchorPane);
            stage.setScene(scene);
            stage.show();
        }
    }

    public void getPrimaryStage(Stage stage) throws Exception
    {
        this.stage = stage;
        createScene(1);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        startGameButton.setOnAction(event -> {
            try {
                createScene(2);
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        });

        endGameButton.setOnAction(event -> {
            stage.close();
        });
    }
}

【问题讨论】:

  • 确实这是该问题的重复,除非您可以提供其他详细信息...例如哪个值是null...堆栈跟踪说什么?
  • 所以当我按下按钮开始游戏时我调用函数createScenes(2) 我的编译器在anchorPane = loader.load(); 线上很生气,当我按下按钮结束游戏时什么也没发生,但它必须关闭我的舞台。跨度>

标签: java javafx fxml fxmlloader


【解决方案1】:

我记得有一个类似的问题,fxml 文件通过 fx:controller 属性链接到控制器文件。您尝试在未处理/加载的控制器中加载 fxml。创建另一个表单,显示/隐藏表单似乎更简单。

【讨论】:

  • 从 fxml 文件中移除 fx:controller 属性并使用 fxmlLoader.setController();动态定义控制器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 2016-09-03
  • 1970-01-01
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多