在JavaFX中初始化GUI的最佳方法是什么? [英] Best way to initialize GUI in JavaFX?

查看:360
本文介绍了在JavaFX中初始化GUI的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在应用程序启动时根据系统信息设置几个ui元素(即这是先验未知的信息,因此要在css或fxml文件中静态设置它)。
控制器构造函数是最好的地方吗?
首先要考虑的是在 start() init()方法中扩展Application的主类,但似乎设置是阻止程序员在节点层次结构中一直轻松访问ui元素。 (另一方面,通过@FXML注入在各自的控制器中非常容易)

I want to set up several ui elements based on system information at the time of the application start up (i.e. this is info not known a priori so to set it statically in the css or the fxml file). Is the controller constructor the best place to do this? A first consideration was to do that either on the start() or init() methods of the main class that extends Application but it seems the set up is rather preventing programmer from easily accessing ui elements all the way down the node hierarchy. (which on the other hand is extremely easy in the respective controller through the @FXML injection)

推荐答案

这取决于你需要做的工作。如果您需要依赖于应用程序阶段的任何内容,请在start方法中执行它。如果没有,则可以在构造函数,init或start方法中执行。请记住,启动机制期望Application子类提供无参数构造函数,因此如果在那里合并启动逻辑,则避免需要构造函数参数。

It depends on the kind of work you need done. If you need anything that relies on your application's stage, then perform it in the start method. If not, then it can be performed in the constructor, init, or start methods. Bear in mind that the launching mechanism expects Application subclasses to provide a no-arg constructor, so if you incorporate startup logic there, then avoid requiring constructor parameters.

但是,如果你打算使用一个控制器(我建议使用),那么这个逻辑应该在它的initialize方法中出现,而不是在你的应用程序类中。

However, if you're going to use a controller (which I would recommend), then this logic should occur in its initialize method, not in your application class.

如果您需要从控制器引用舞台,那么您可以找到许多此类解决方案,以便在SO上将引用传递给控制器​​,例如制作舞台在应用程序类中引用public和static,或者在控制器中有一个可以从应用程序的start方法设置的字段。

If you need a reference to the stage from the controller, then you can find many such solutions to passing the reference to the controller here on SO, such as making the stage reference public and static in your application class, or having such a field in your controller that can be set from your application's start method.

这篇关于在JavaFX中初始化GUI的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆