2016-10-31 40 views
0

我开始使用它自己的控制器的第二个场景。我想从另一个类访问该控制器中的一个方法。我如何获得新的场景控制器的句柄?如何获得新阶段的控制器控制器JavaFX

public void startNewScene() throws IOException{ 
    Stage stage = new Stage(); 
    Partent root; 
    root = FXMLLoader.load(getClass().getResource("fxmlfile.fxml"); 
    Scene scene = new Scene(root); 
    Stage.setScene(scene); 
    stage.show(); 

} 

回答

2

创建FXMLLoader实例(而不是使用静态load(...)方法),并从它那里得到控制器:

public void startNewScene() throws IOException{ 
    Stage stage = new Stage(); 
    FXMLLoader loader = new FXMLLoader(getClass().getResource("fxmlfile.fxml")); 
    Parent root = loader.load(); 
    MyController controller = loader.getController(); 
    Scene scene = new Scene(root); 
    Stage.setScene(scene); 
    stage.show(); 
} 

显然与控制器fxmlfile.fxml的实际的类名称替换MyController

+0

我得到ClassCastException AnchorPane无法转换为FXMLLoader。我也将其更改为BorderPane,我得到相同的错误无法投射到FXMLLoader – Moe

+0

@Moe你复制了我的代码错误 –

+0

你是对的!而不是做新的FXMLLoader(getClass())我做了FXMLLoader.load(getClass()); thx为您的帮助! – Moe