0

当我按下 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();
        });
    }
}
4

1 回答 1

0

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

于 2016-03-25T21:42:45.603 回答