我看了很多页面试图找出如何切换场景,但我没有成功.
我有一个计算器,我的目标是选择一个菜单选项来改变计算器(即:基本和科学).现在我只是测试所以这里是我的代码到目前为止与这个问题相关(我使用的是Scene Builder):
@FXML private MenuItem basic;
@FXML private MenuItem testSwitch;
public static void main(String[] args)
{
Application.launch( args );
}
@Override
public void start(Stage primaryStage) throws Exception
{
Parent pane = FXMLLoader.load(
getClass().getResource( "calculator.fxml" ) );
Scene scene = new Scene( pane );
primaryStage.setScene(scene);
primaryStage.setTitle( "Calculator" );
primaryStage.show();
}
@FXML
public void handleMenuOption(ActionEvent e)
{
if(e.getSource()==basic)
{
changeScene("calculator.fxml");
}
else if(e.getSource()==testSwitch)
{
changeScene("TestSwitch.fxml");
}
}
public void changeScene(String fxml)
{
//this prints out
System.out.println(fxml);
}
Run Code Online (Sandbox Code Playgroud)
编辑 我已经尝试了很多东西.无论如何,我总是得到这个NullPointerException.我觉得它可能与在场景构建器中设置某些内容有关,但我一直无法找到答案
Exception in …Run Code Online (Sandbox Code Playgroud) 我在选择menuItem时关闭当前场景并打开另一个场景时遇到问题.我的主要阶段编码如下:
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Shop Management");
Pane myPane = (Pane)FXMLLoader.load(getClass().getResource
("createProduct.fxml"));
Scene myScene = new Scene(myPane);
primaryStage.setScene(myScene);
primaryStage.show();
}
Run Code Online (Sandbox Code Playgroud)
然后在createProduct.fxml中,当menuItem是onclick时,它将执行以下操作:
public void gotoCreateCategory(ActionEvent event) throws IOException {
Stage stage = new Stage();
stage.setTitle("Shop Management");
Pane myPane = null;
myPane = FXMLLoader.load(getClass().getResource("createCategory.fxml"));
Scene scene = new Scene(myPane);
stage.setScene(scene);
stage.show();
}
Run Code Online (Sandbox Code Playgroud)
它确实打开了createCategory.fxml.但是,以前的createProduct.fxml面板不会关闭.我知道有一个叫做stage.close()的东西要做这个,但我不知道在哪里实现它,因为我没有从一开始就从主右侧传递场景.我想知道我应该怎么解决这个问题.
提前致谢.