Reputation: 209
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.
Upvotes: 0
Views: 1438
Reputation: 13859
((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!
});
Upvotes: 3