菜單MenuBar Menu MenuItem
調用Frame對象的setMenuBar()方法,設置菜單,參數:MenuBar對象
import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Menu; import java.awt.MenuBar; import java.awt.MenuItem; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class MenuBarDemo { private Frame frame; private MenuBar menuBar; private Menu menu; private Menu subMenu; private MenuItem menuItem; public MenuBarDemo() { init(); addEvents(); } public void init() { frame = new Frame("菜單測試"); frame.setBounds(300, 200, 500, 400); frame.setLayout(new FlowLayout()); // 菜單欄 menuBar = new MenuBar(); // 菜單 menu = new Menu("文件"); // 菜單項 menuItem = new MenuItem("退出"); // 菜單添加菜單項 menu.add(menuItem); // 菜單欄添加菜單 menuBar.add(menu); frame.setMenuBar(menuBar); frame.setVisible(true); } public void addEvents(){ frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); //菜單點擊 menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); } /** * @param args */ public static void main(String[] args) { new MenuBarDemo(); } }