JAVA javaFX menuBar, multiple items, one method (scene Builder)

I have a window built with scene builder with a menuBar. In the menuBar there are a couple of Menuitems that only open other windows.

So I want to write only one function that can be used by each one of those menuItems, and open the appropriate window.

I tried to give an id for each menuItem, and with this function

public void openWindow(ActionEvent event){ 
    System.out.println( event);
}

I can see that id (example : customer menuItem) ,

javafx.event.ActionEvent[source=MenuItem[id=customers, styleClass=[menu-item]]]

But I dont know how to get it to use it to open the customer window.

Answer

In order to get id from ActionEvent you should cast the source of it to MenuItem:

public void openWindow(ActionEvent event){
    MenuItem source = (MenuItem) event.getSource();
    System.out.println(source.getId());
}

note, that if you are not sure that the source of event is of type MenuItem you can check it like so:

if (event.getSource() instanceof MenuItem) {
     MenuItem source = (MenuItem) event.getSource();
     System.out.println(source.getId());
}

Leave a Reply

Your email address will not be published. Required fields are marked *