如何从FXML文档加载特定容器?

时间:2021-03-29 17:02:29

I am building application which has different interfaces. I have decided to use the JavaFX for this and I wanted to know if I could have multiple containers saved in the FXML document and when using the the FXML Loader, pick a specific container by the id (i.e., fx:id).

我正在构建具有不同接口的应用程序。我决定使用JavaFX,我想知道我是否可以在FXML文档中保存多个容器,并且在使用FXML Loader时,通过id(即fx:id)选择一个特定的容器。

I have recently come to know that several people grouped against me and make question duplicate. I will now state my defence and prove this is not duplicate.

我最近才知道,有几个人反对我并提出问题重复。我现在陈述我的辩护并证明这不重复。

What that question doesn't answer mine is the fact that I want to set fx:id for parent itself and use the fxmlloader to load parent on basis of id. Ok?

这个问题没有回答我的问题是我想为父本身设置fx:id并使用fxmlloader在id的基础上加载父。好?

1 个解决方案

#1


2  

You can do that using the FXML loader's getNamespace method.

您可以使用FXML加载器的getNamespace方法来实现。

(code from this SO answer, but see comments):

(来自此SO答案的代码,但请参阅评论):

FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
Parent root = loader.load();
TextField foo = (TextField)loader.getNamespace().get("exampleFxId");

A better approach is to have separate fxml files for all your needs and then load each one as needed with the FXMLLoader.load() method.

更好的方法是为您的所有需求提供单独的fxml文件,然后根据需要使用FXMLLoader.load()方法加载每个文件。

#1


2  

You can do that using the FXML loader's getNamespace method.

您可以使用FXML加载器的getNamespace方法来实现。

(code from this SO answer, but see comments):

(来自此SO答案的代码,但请参阅评论):

FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
Parent root = loader.load();
TextField foo = (TextField)loader.getNamespace().get("exampleFxId");

A better approach is to have separate fxml files for all your needs and then load each one as needed with the FXMLLoader.load() method.

更好的方法是为您的所有需求提供单独的fxml文件,然后根据需要使用FXMLLoader.load()方法加载每个文件。