javafx - 当它被激活时,我可以在 Action Event 方法中获取 javafxml 对象的 id 吗?
问题描述
我正在尝试编写一个小型 rpg 代码,我决定将基础知识放入一个 fxml 文档(MenuBar 及其项目)。所以现在我计划在您单击菜单项(角色、库存和设备)时打开一个新窗口,这样我就可以在一个额外的窗口中显示这些东西。因此,我想将每个菜单的标题设置为与 MenuItem 上显示的文本等效是有道理的。当然,我可以为每个菜单项创建一个额外的方法,但我正在寻找一种可能性,我可以在其中获取触发事件的菜单项的 id,因此我可以使用他们的 getText 方法来获取标签. 有人可以帮助我吗?
我尝试使用“this”访问对象,还考虑使用枚举将 ID 连接到枚举 MenuName 的对象,所以我只需在我的方法中放置一个开关,从而创建菜单,但这也没有t 工作,因为在那里我无法检查哪些 id 被解雇了。所以对于我程序的那一部分,它没有帮助。
这是我的控制器类中的代码
public class Controller {
@FXML
private void menuIsClickedDefault(ActionEvent event) throws Exception {
Stage secondStage = new Stage();
Parent a = FXMLLoader.load(getClass().getResource("menus.fxml"));
secondStage.setTitle(HERES_MY_PROBLEM);
secondStage.setScene(new Scene(a, 646, 400));
secondStage.initModality(Modality.APPLICATION_MODAL);
secondStage.show();
}
}
这些是我的 fxml 对象:
<MenuItem fx:id="stats" mnemonicParsing="false" text="Statistics" />
<MenuItem fx:id="inv" mnemonicParsing="false" text="Inventory" />
<MenuItem fx:id="equip" mnemonicParsing="false" text="Equipment" />
我还没有将方法集成到对象中,因为如果不解决问题就没有意义,而且我知道由于设置的类似方法,其余代码正在工作。
解决方案
您可以调用event.getSource()
以检索触发事件的节点。不过,您需要将返回的对象转换为正确的类型。
private void menuIsClickedDefault(ActionEvent event) throws Exception {
Stage secondStage = new Stage();
Parent a = FXMLLoader.load(getClass().getResource("menus.fxml"));
// Get the source of this event and cast it to a MenuItem; then you can
// retrieve its text property
secondStage.setTitle(((MenuItem) event.getSource()).getText());
secondStage.setScene(new Scene(a, 646, 400));
secondStage.initModality(Modality.APPLICATION_MODAL);
secondStage.show();
}
推荐阅读
- python - PDF 文档不包含 utf-8 编码
- javascript - 从嵌套访问包含唯一数据集属性的特定元素s
- security - pdfbox - 如何以增量方式签署更新的文档或更改
- python - 如何在公会中获取每个成员的ID
- reactjs - 有没有办法在 React 的函数中调用你的主要组件?
- javascript - 我在 vue js 的样式标签中加载背景图像时遇到问题
- java - 在Java中将double转换为无符号整数
- html - 在 HTML 的 vs 代码中禁用波浪黄色下划线
- python - 将图像转换为范围为 [0,255] 而不是 [0,1] 的张量?
- python - Conway 的生命游戏 Python / PyGame 打印错误