I looked online but I couldn't find it. How can I get the name of the clicked menu item when somebody clicks it.I want to change the scene according to the clicked menu item but I don't want to create 8 different methods. If I can get the name of the clicked menu item I can create 1 method that takes that name as a parameter and launches the FXML Loader and changes the scene
Asked
Active
Viewed 261 times
-2

Cem Oner
- 23
- 5
-
1work through a tutorial on how to use Menu/Items (should give you an idea of how to do), apply what you learned to your context, when stuck come back with a [mcve] demonstrating what's not working as expected :) – kleopatra Jan 08 '21 at 16:48
2 Answers
0
Register an inline listener to the MenuItem(s) onAction event in the initialization method.
for (MenuItem item : menu.items()) {
item.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
processCategory(item.getText()); // this would do your thing you want to do.
event.consume();
});
}
-
the answer is okay, the comment is plain wrong: event handlers are always notified on the fx thread – kleopatra Jan 08 '21 at 23:05
-
Yeah, I may have been thinking of ListChangeEvents ;) I haven't touched Javafx in a year. – Jan 08 '21 at 23:06
-2
As is mentioned here: https://www.programcreek.com/java-api-examples/?class=javafx.scene.input.MouseEvent&method=getSource
You can do it like:
private void handleLabel(MouseEvent event) {
Node label = (Node) event.getSource();
System.out.println("Mouse click on label: " + label.getId());
}

MrFisherman
- 720
- 1
- 7
- 27
-
-
-
Like here: https://stackoverflow.com/a/40758244/10802597 i believe there is some kind of setOnMouseClickListener or something like this – MrFisherman Jan 08 '21 at 16:49