java 一个 FXML 文件的多个控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16879826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:15:12  来源:igfitidea点击:

Multiple controller for one FXML file

javajavafx-2javafxfxml

提问by RN Hindarwan

I have one fxml file controlled by one controller. I want to separate the controller into multiple parts as if placed in one controller makes a long code. Unfortunately, fx:controller can only be placed in the root. Are there any suggestions for me how to separate the controller?

我有一个由一个控制器控制的 fxml 文件。我想将控制器分成多个部分,就好像放在一个控制器中会生成一个长代码一样。不幸的是,fx:controller 只能放在根目录中。对我如何分离控制器有什么建议吗?

回答by Puce

I recommend to create custom controls - use several smaller FXML files rather than one big FXML file.

我建议创建自定义控件 - 使用几个较小的 FXML 文件而不是一个大的 FXML 文件。

Here is the tutorial:

这是教程:

http://docs.oracle.com/javafx/2/fxml_get_started/custom_control.htm

http://docs.oracle.com/javafx/2/fxml_get_started/custom_control.htm

回答by scottb

During the loading of your FXML markup, there is only the provision to have one controller specified for your scene graph. You are able to load other FXML markup files and nest controllers, but I don't think that's what you're asking.

在加载 FXML 标记期间,只提供为场景图指定一个控制器。您可以加载其他 FXML 标记文件和嵌套控制器,但我认为这不是您要问的。

To my mind, it doesn't matter anyway.

在我看来,无论如何都无所谓。

You can write any number of classes in any number of files and have them interact with your controller class just like any Java class can interact with any other Java class.

您可以在任意数量的文件中编写任意数量的类,并让它们与您的控制器类进行交互,就像任何 Java 类都可以与任何其他 Java 类进行交互一样。

I really can't think of any particularly good reason why it would be useful to specify multiple controllers for a scene graph at load time.

我真的想不出有什么特别好的理由说明为什么在加载时为场景图指定多个控制器会很有用。

回答by Giovanni Contreras

You can add an fxml file as a node into another fxml , both with diferent controllers with include option in scene builder

您可以将一个 fxml 文件作为节点添加到另一个 fxml 中,两者都具有不同的控制器和场景构建器中的包含选项

回答by muhammad usman

By this way you make another controller of the same FXML file:

通过这种方式,您可以使用相同的 FXML 文件制作另一个控制器:

MyClass object= new MyClass();
FXMLLoader  root = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
root.setController(object);