Menubars and menus take care of displaying themselves, but attaching behavior to menu items is something you must handle yourself. Example 17-2 expands FileMenuTest to print the label of the item selected and to quit the application when the “Quit” item is selected.
Since menu items fire action events when they are selected, an implementation of ActionListener obtains a reference to the menu item that generated the event and prints the label associated with the menu item. If the menu item is the Quit menu item, we exit the application, being careful to dispose of the frame before exiting. So that In order for the MenuItemListener to do its thing, it is added as the action listener for every menu item created.