GUI图形编程(10)---菜单组件

GUI图形编程(10)---菜单组件_第1张图片

package org.lanqiao.menu.demo;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

public class MenuDemo {
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		frame.setTitle("菜单组件");
		frame.setSize(500, 500);
		frame.setLocationRelativeTo(null);
		//获取frame默认的面板
		JPanel  panel = (JPanel) frame.getContentPane();
		panel.setLayout(new BorderLayout());
		//创建一个菜单条
		JMenuBar  mb = new JMenuBar();
		//创建菜单
		JMenu  fileMenu = new JMenu("文件");
		JMenu  startMenu = new JMenu("开始");
		JMenu  insertMenu = new JMenu("插入");
		JMenu  taskMenu = new JMenu("任务");
		//创建菜单项
		JMenuItem newFile = new JMenuItem("新建");
		JMenuItem saveFile = new JMenuItem("保存");
		JMenuItem saveFile2 = new JMenuItem("另存为");
		JMenuItem exitFile = new JMenuItem("退出");
		//将菜单添加到菜单条
		mb.add(fileMenu);
		mb.add(startMenu);
		mb.add(insertMenu);
		mb.add(taskMenu);
		//将菜单项添加到菜单中
		fileMenu.add(newFile);
		fileMenu.add(saveFile);
		fileMenu.add(saveFile2);
		fileMenu.add(exitFile);
		
		panel.add(mb,BorderLayout.NORTH);
		
		frame.setVisible(true);
		newFile.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				String cmd = e.getActionCommand();
				System.out.println(e.getSource());
				if(cmd.equals("新建")) {
					System.out.println("New  File");
				}
			}
		});
	}
}

 

 

 

 

 

 

 

 

你可能感兴趣的:(GUI图形编程)