简体   繁体   English

JavaFX FXML-使用fx:id获取MenuItem

[英]JavaFX FXML - Getting MenuItem using fx:id

I am building the GUI of a Java application using Scene Builder. 我正在使用Scene Builder构建Java应用程序的GUI。 For each element, I have given it a fx:id so that I can refer to them later. 对于每个元素,我都给了它一个fx:id以便以后可以参考它们。 I need to use setOnAction() on many of its elements such as: 我需要在其许多元素上使用setOnAction() ,例如:

((Button)mainPane.lookup("#submitButton")).setOnAction(e->{
    // ... code triggered when button is pressed ...
});

This works for most elements except MenuItem s. 这适用于MenuItem以外的大多数元素。 When I try the following, Eclipse tells me "Cannot cast from Node to MenuItem " and it does not work. 当我尝试以下操作时,Eclipse告诉我“无法从Node投射到MenuItem ”,并且它不起作用。

// Does not work
((MenuItem)mainPane.lookup("#about")).setOnAction(e->{
    // ... take user to about page ...
});

I see that MenuItem only extends Object , so it cannot be casted from a Node . 我看到MenuItem仅扩展了Object ,因此无法从Node进行强制转换。 How can I get back the MenuItem using its fx:id ? 如何使用其fx:id取回MenuItem

Note: I know I could use the On Action of FXML, but I want to utilize Lambda functions and keep the event-handling code in the same style. 注意:我知道我可以使用FXML的On Action ,但是我想利用Lambda函数并使事件处理代码保持相同的样式。

((Button)mainPane.lookup("#submitButton")) <- is a terrible idea. ((Button)mainPane.lookup("#submitButton")) <-是一个糟糕的主意。

If your nodes have an fx:id . 如果您的节点具有fx:id You should do @FXML YourNodeType yourNodeFx:Id; 您应该执行@FXML YourNodeType yourNodeFx:Id;

Example: In the FXML your Button's fx:id="submitButton" . 示例:在FXML中,您Button's fx:id="submitButton" Your Controller code should look like: 您的Controller代码应如下所示:

@FXML Button submitButton;

In your initialize method you should do: 在您的initialize方法中,您应该执行以下操作:

submitButton.setOnAction(event ->{
    //Your code here!
});

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

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