无法从 JavaFX 中的 MenuItem 获取场景
问题描述
我正在尝试根据 menuItem 单击更改 javafx 阶段中的场景.这是我的 sample.fxml:
I am trying to change the scene in a javafx stage based on menuItem click. Here is my sample.fxml:
这是我的 Controller.java:
Here is my Controller.java:
这是我的 Main.java:
Here is my Main.java:
当我点击 Accounts Menu 下的 menuItem Manage 时,出现以下异常:
When I click on the menuItem Manage under Accounts Menu, I get the following exception:
那么如何从菜单项单击事件处理程序中获取包含阶段/场景?
So how do I get the containing stage/scene from the menu Item clicked event handler?
编辑线
在 controller.java 中是第 29 行,这会产生问题.
in controller.java is line number 29 which is giving problems.
推荐答案
你真正的错误显示在堆栈跟踪的倒数第二行:
Your real error is shown in the second to last line of the stack trace:
此错误指的是控制器中的以下行:
This error is referring to the following line from your controller:
查看 JavaFX API 文档,MenuItem 和 Menu 都不是 Node 的子类.http://docs.oracle.com/javafx/2/api/javafx/场景/控制/MenuItem.htmlhttp://docs.oracle.com/javafx/2/api/javafx/场景/控制/Menu.html
Looking at the JavaFX API Docs, neither MenuItem nor Menu are subclasses of Node. http://docs.oracle.com/javafx/2/api/javafx/scene/control/MenuItem.html http://docs.oracle.com/javafx/2/api/javafx/scene/control/Menu.html
我建议将源作为对象获取,然后在继续之前检查其类型.另外,我在使用 getSource() 方法时遇到了问题;getTarget() 方法对我来说效果更好.不管怎样,你仍然需要一种方法来进入舞台.
I would suggest grabbing the source as an Object, then checking its type before continuing. Also, I ran into problems using the getSource() method; the getTarget() method worked better for me. Either way, you still need a way to get the to the Stage.
为此,您可能希望在 FXML 中使用 fx:id
标签,而不是 id
标签.这将允许您将 FXML 元素直接注入到您的控制器中.例如,您可以通过将 MenuBar 元素注入控制器来从 MenuBar(它是 Node 的子类)中获取舞台.
To do this, you might want to use the fx:id
tag in your FXML instead of the id
tag. This will allow you to inject the FXML elements directly into your controller. For example, you could grab the Stage from the MenuBar (which is a subclass of Node) by injecting the MenuBar element into your controller.
在 FXML 中:
在控制器中:
您可能需要在此处进行一些调整,但希望对您有所帮助.
You may need to do a bit of tweaking here, but hopefully it helps.
这篇关于无法从 JavaFX 中的 MenuItem 获取场景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!