Menu bar JMenuBar, menu jmenu, food item JMenuItem
Once a has a submenu item, A is the menu JMenu instead of the menu item JMenuItem
Importjavax.swing.*;Importjava.awt.event.ActionEvent;ImportJava.awt.event.ActionListener;Importjava.awt.event.KeyEvent; Public classDemoextendsJFrame { PublicDemo () {Settitle ("Menu Bar"); SetBounds (100,100,200,200); Setdefaultcloseoperation (Windowconstants.exit_on_close); JMenuBar MenuBar=NewJMenuBar ();//Menu BarSetjmenubar (MenuBar);//Set as a menu bar for a form//Menu 1JMenu menu=NewJMenu ("menu (F)");//Menumenubar.add (menu); Menu.setmnemonic (keyevent.vk_f);//shortcut key Alt+fJMenuItem MenuItem=NewJMenuItem ("menu item (O)");//menu itemmenu.add (MenuItem); Menuitem.addactionlistener (NewItemListener ());//add an action listener to a menu itemIcon icon=NewImageIcon ("src/img. JPG ");//the logo of the menu itemMenuitem.seticon (icon); Menuitem.setmnemonic (keyevent.vk_o);//shortcut alt+f After opening the menu, press Omenu.addseparator ();//after the menu item, add a separator lineJMenu Menu12=NewJMenu ("menu 12");//Once there is a subclass, it is a menu, not a menu item. menu.add (MENU12); JMenuItem menuItem121=NewJMenuItem ("menu item 121"); JMenuItem menuItem122=NewJMenuItem ("menu item 122"); Menu12.add (menuItem121); Menu12.add (menuItem122); Menuitem121.addactionlistener (NewItemListener ());//add an action listener to a menu itemMenuitem122.addactionlistener (NewItemListener ());//add an action listener to a menu item//Menu 2JMenu menu2=NewJMenu ("Menu 2"); Menubar.add (MENU2); } Public Static voidMain (string[] args) {Demo frame=NewDemo (); Frame.setvisible (true); } Private classItemListenerImplementsactionlistener{//Custom Action Monitoring Public voidactionperformed (ActionEvent e) {JMenuItem MenuItem= (JMenuItem) e.getsource ();//get the menu item that triggered this eventSystem.out.println ("Clicked menu item is:" +menuitem.gettext ());//Get text } }}
Advanced Components--menu bar JMenuBar