激活后,我可以在Action Event方法中获取javafxml对象的ID吗?

时间:2019-05-23 13:14:02

标签: javafx fxml scenebuilder

我试图编写一个小的rpg,我决定将基础知识放入fxml文档(带有其项目的MenuBar)中。 因此,现在我打算在单击菜单项(字符,库存和设备)时打开一个新窗口,这样我可以显示一个额外的窗口。因此,我想将每个菜单的标题设置为与MenuItem上显示的Text等效。当然,我可以为每个菜单项添加一个额外的方法,但是我正在寻找一种可能性,可以在该菜单项中触发事件的菜单项的ID,因此可以使用其getText方法来获取标记。 有人可以帮我吗?

我试图使用“ this”访问对象,并且还考虑过使用枚举将ID连接到枚举MenuName的对象,所以我只需要在方法中放入一个开关,从而创建菜单,但是也没有解决,因为在那里我无法检查哪些身份证被解雇了。因此,对于我的程序的那部分,它没有帮助。

这是我的控制器类中的代码

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" />

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

1 个答案:

答案 0 :(得分:5)

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