[javaSE] GUI(選單)

weixin_34162629發表於2016-06-15

選單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();
    }

}

相關文章