简体   繁体   中英

JavaFX FXML - Getting MenuItem using fx:id

I am building the GUI of a Java application using Scene Builder. For each element, I have given it a fx:id so that I can refer to them later. I need to use setOnAction() on many of its elements such as:

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

This works for most elements except MenuItem s. When I try the following, Eclipse tells me "Cannot cast from Node to MenuItem " and it does not work.

// 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 . How can I get back the MenuItem using its fx:id ?

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.

((Button)mainPane.lookup("#submitButton")) <- is a terrible idea.

If your nodes have an fx:id . You should do @FXML YourNodeType yourNodeFx:Id;

Example: In the FXML your Button's fx:id="submitButton" . Your Controller code should look like:

@FXML Button submitButton;

In your initialize method you should do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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