【问题标题】:Java FX - Associate a second fxml file to a second controller fileJava FX - 将第二个 fxml 文件关联到第二个控制器文件
【发布时间】:2017-08-16 12:07:20
【问题描述】:

我尝试开发一个应用程序并且我在 Eclipse 上工作。

首先我处理了四个文件:

  • Main.java,使用 sheet1.fxml 文件启动界面

  • MyController.java,声明 fxml 文件 sheet1 的按钮和锚点。该文件实现了一个动作事件:在单击第一个 fxml 文件(即 sheet1)的按钮后进入第二个界面(sheet2.fxml)。 p>

现在我想处理第二个接口 sheet2.fxml。我想:
- 根据文件夹中的文件数量添加文本
- 创建按钮以进入第三个界面

但我的问题是我该怎么做?
我尝试创建第二个控制器来声明 Text nbExcel 和按钮,然后建立与 sheet2.fxml 文件的关系,但我没有看到诀窍。
如何关联运行位于该 sheet2 和新控制器上的组件的事件?

我开始在“myController2”上这样做:

       public class myController2 extends Application {

        // How and where to associate that controller with the fxml file "sheet2" ?

      public void start2() throws IOException{
      Stage primaryStage2 = new Stage();

      Parent root = FXMLLoader.load(getClass().getResource("sheet1.fxml"));
      Scene scene = new Scene(root,400,400);

scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
      primaryStage2.setScene(scene);
      primaryStage2.show();
      }

       @FXML
       // declaration text in order to count files in folder in sheet2 interface
       private Text nbExcel;

       // declaration action buttons in sheet2 interface
       // To do


       // 1 - INITIALISATION
       public void initialize(URL location, ResourceBundle resources) {

           File a = new File("C:/Controles/Excel");
           int b = 0;
           for (File file : a.listFiles()) {
           if (file.isFile() && (file.getName().endsWith(".xlsx") )) {
              b++;
            }
           }
           nbExcel.setText(Integer.toString(b));
       }

任何帮助将不胜感激。
谢谢!

【问题讨论】:

  • 请写a minimal, complete, and verifiable example。我没有阅读您的代码,因为它太长了,我敢肯定其中 90% 是不必要的混乱。
  • 此外,您似乎需要帮助的部分是您没有发布但只是试图描述的部分。代码描述很少有用。 “我应该为每个工作表创建另一个控制器类吗?”:是的。每个 FXML 文件都应该有自己的控制器类。
  • 好吧,对不起.. 我对我的第一篇文章进行了编辑。非常感谢您的帮助

标签: java javafx controllers


【解决方案1】:

为了连接 fxml 文件并创建新场景,您可以执行以下操作:

        Stage primaryStage = new Stage();

        Parent root = FXMLLoader.load(getClass().getResource("/application/sheet2.fxml"));
        Scene scene = new Scene(root,400,400);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();

编辑:确认这段代码应该在您在问题中显示的控制器类中。

【讨论】:

  • 感谢您的帮助。我将您的 sn-p 置于公共空白中(请参阅我的编辑),但它不起作用。新控制器似乎与 fxml 文件没有关联。。谢谢
  • 嗯。我不确定那是什么问题。如果你使用它,也许你需要在 SceneBuilder 中连接它们。 @朱利安
  • 我在 myController2 中粘贴了“View - Show Sample Controller Skeleton”的内容,但不幸的是结果相同..
猜你喜欢
  • 2020-09-14
  • 1970-01-01
  • 2011-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多