Java 如何获取当前加载的fxml文件的名称?
我有Java 如何获取当前加载的fxml文件的名称?,java,javafx,fxml,borderpane,Java,Javafx,Fxml,Borderpane,我有BorderPane,分为3个AnchorPanes,它们不断变化。是否可以获取完整的.fxml文件名,如“MainScreen.fxml”?我可以使用System.out.println(getRootLayout().getCenter())获取AnchorPane,但我不知道如何获取它的名称 只是我需要从主类调用位于我的一个控制器中的方法。但我只想在控制器的某些fxml文件当前正在使用时调用它 简而言之:如果MainScreen.fxml正在使用,我将调用它的MainScreenCon
BorderPane
,分为3个AnchorPane
s,它们不断变化。是否可以获取完整的.fxml
文件名,如“MainScreen.fxml”?我可以使用System.out.println(getRootLayout().getCenter())获取AnchorPane
代码>,但我不知道如何获取它的名称
只是我需要从主类调用位于我的一个控制器中的方法。但我只想在控制器的某些fxml文件当前正在使用时调用它
简而言之:如果MainScreen.fxml正在使用,我将调用它的MainScreenController方法,如果没有,那么我就不会调用它。基于您的问题,我假设每个AnchorPane都是从不同的fxml文件加载的,并且您在应用程序中保留对其控制器的引用
一个简单的解决方案是将文件信息放入控制器
您可以手动执行此操作
URL location = getClass().getResource("MainScreen.fxml");
FXMLLoader fxmlLoader = new FXMLLoader(location);
// ... more fxmlLoader configuration ...
fxmlLoader.load();
// assuming your own Controller class has a setLocation method
Controller c = (Controller) fxmlLoader.getController();
c.setLocation(location);
。。。或者依赖FXMLLoader
// your own Controller class
public class Controller
{
// the URL will be automatically injected by the FXMLLoader
// careful: the name of the field must be 'location'
@FXML
private URL location;
// ...
}
然后,您可以简单地向控制器添加一个getLocation()
方法,以检查它是从哪个文件加载的
但是,对于您的潜在问题,可能有一个更好的解决方案,它不需要检查特定的文件名。没有内置的方法可以做到这一点;您只需要从第一次加载它的位置存储它。但你为什么需要这个?似乎有一种更好的方法可以满足您的需要。一个好的解决方案是将初始化CustomControl的代码移动到一个新类(如UserControl)中,并将FXML文件存储在一个受保护的变量中。