1

我目前正在将一个小型应用程序从 Swing 重新编码为 JavaFX,因为它似乎是部署我目前拥有的 web 的最简单方法。

我似乎无法做一些非常简单的事情,而且我在文档和其他帖子中迷失了方向:

无论如何,我有调用相关 FXML 文件的主控制器:

public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));

    Scene scene = new Scene(root);

    stage.setScene(scene);
    stage.show();
}

现在,从 Login.fxml 中,我有一个按钮,我希望该按钮打开另一个 FXML 文件。我可以让按钮成功加载事件,但我尝试了很多东西,但我无法让它工作。我正在尝试这样的事情:

private void handleButtonAction(ActionEvent event){

    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("GeneradorBases.fxml"));

   // fxmlLoader.setRoot(this); 
  //  fxmlLoader.setController(this);

    try {
        fxmlLoader.load(); 

    }
    catch (IOException e){
       throw new RuntimeException(e); 
    }
}

我尝试按照我在 Stackoverflow 上看到的示例进行操作。基本上 .setRoot 和 .setController 会使应用程序崩溃。甚至 .load() 也这样做。

关于如何完成这项工作的任何建议?

4

3 回答 3

3

鉴于您列出的例外情况,您需要设置所有标记为@FXML和类的字段packet.OtherControllerController public

更新:您的另一个问题是您没有将 FXML 加载的结果分配给任何东西。

public class FirstController implements Initializable {

  @FXML
  public void handleButtonAction(ActionEvent event) throws Exception{
    Node node = (Node) event.getSource();
    Stage stage = (Stage) node.getScene().getWindow();
    Scene scene = stage.getScene();

    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Second.fxml"));
    Parent root = (Parent) fxmlLoader.load();          

    scene.setRoot(root);
  }
}

有关扩展示例,请参见教程:http: //docs.oracle.com/javafx/2/get_started/fxml_tutorial.htm

于 2012-11-05T11:22:14.143 回答
1

您的解决方案对fxmlLoader.load(). 为了显示加载的 FXML 文件,您需要以某种方式将返回的值传递给您的主控制器(或应管理舞台或场景的代码的另一部分)并将其设置为新根(或例如窗格的子级)应在其中显示)。

于 2012-11-05T08:34:46.263 回答
1

如果提供的解决方案没有帮助,您可以尝试以下代码(对我来说这是可行的):

final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/page.fxml"));
      父根 = (父) fxmlLoader.load();

      场景 nscene = 新场景(根);
      阶段 tStatge = new Stage();
      tStatge.setScene(nscene);
      tStatge.show();
于 2014-02-10T14:25:33.040 回答