简体   繁体   English

JavaFX将FXML添加到普通的Java控制器中

[英]JavaFX adding FXML to and plain java controllers

My first post, be gentle please. 我的第一篇文章,请保持温柔。

I am making a JavaFX GUI for a simple game. 我正在为一个简单的游戏制作JavaFX GUI。 I have an FXML layout loaded via FXML file loader here: 我在这里通过FXML文件加载器加载了FXML布局:

Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));

Then I create a button in Main.java: 然后在Main.java中创建一个按钮:

Button button = new Button("Jp", view);

And in order to display: 并且为了显示:

primaryStage.setScene(new Scene(root));
primaryStage.show();

Question: How on earth I can combine FXML layout and plain java Button object to be on the same scene ? 问:到底我怎样才能将FXML布局和纯Java Button对象结合在同一场景上? Is it like apples and oranges, impossible to combine ? 难道像苹果和橘子一样,不可能结合在一起吗? My IDE is not letting me invoke the method recomended from java docs: 我的IDE不允许我调用从Java文档推荐的方法:

root.getChildren().add();

and so on... 等等...

Please help me and/or point me in some direction, I really tried... 请帮助我和/或为我指明方向,我确实尝试过...

The getChildren() method defined in Parent is a protected method: therefore you cannot access it from your Main class, which is why your code won't compile. Parent定义getChildren()方法是一个protected方法:因此,您不能从Main类访问它,这就是为什么您的代码无法编译的原因。

Pane overrides this method and makes it public , so assuming the root element of your FXML file is a Pane (or subclass of Pane ), you just need to be more specific about the type of root. Pane重写此方法并将其public ,因此,假设FXML文件的根元素是Pane (或Pane子类),则只需更详细地说明根的类型。 In other words, again assuming your FXML is as I expect, change 换句话说,再次假设您的FXML符合我的预期,

Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));

to

Pane root = FXMLLoader.load(getClass().getResource("sample.fxml"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM