当我按下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();
});
}
}
答案 0 :(得分:0)
我记得这样的问题,fxml文件通过fx:controller属性链接到控制器文件。您尝试在未处理/加载的控制器中加载fxml。创建另一个表单并显示/隐藏表单似乎更简单。