首页 > 解决方案 > 当它被激活时,我可以在 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" />

我还没有将方法集成到对象中,因为如果不解决问题就没有意义,而且我知道由于设置的类似方法,其余代码正在工作。

标签: javafxfxmlscenebuilder

解决方案


您可以调用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();
}

推荐阅读