利用JAVA创建简单的菜单界面

package com.Gui.test3;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class make extends JFrame{
	//JFrame f = new JFrame("This is a test");
	private JMenuBar bar;
	private JMenu mainMenu[];
	private JMenuItem item[];
	private String stmainMenu[] = {"文件", "编辑", "退出"};
	private String stitemName[] = {"新建", "打开", "关闭"};
	public static void main(String[] args) {
		make te = new make();
		te.GUID();
	}
	
	public make()
	{
		super("This is a test");
	}
	public void GUID()
	{
		bar = new JMenuBar();
		//设定主菜单
		mainMenu = new JMenu[stmainMenu.length];
		for(int i = 0; i < stmainMenu.length; i++)
		{
			mainMenu[i] = new JMenu(stmainMenu[i]);
		}
		
		//加载主菜单栏
		for(int i = 0; i < stmainMenu.length; i++)
		{
			bar.add(mainMenu[i]);
		}
		this.setJMenuBar(bar);
		
		//加载第一项的子菜单
		item = new JMenuItem[stitemName.length];
		for(int i = 0; i < stitemName.length; i++)
		{
			item[i] = new JMenuItem(stitemName[i]);
		}
		mainMenu[0].add(item[0]);
		mainMenu[0].add(item[1]);
		mainMenu[0].add(item[2]);
		
		
		//加载监听器
		item[0].addActionListener
		( 
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					JOptionPane.showMessageDialog(null, "文件");
				}
			}
		);
		
		item[2].addActionListener
		(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent Event)
				{
					System.exit(1);
				}
			}
		);
		
		mainMenu[1].addActionListener
		(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent Event)
				{
					System.exit(1);
				}
			}
		);
		//显示界面;
		this.setSize(300, 300);
		this.setVisible(true);
	}
	
}
以下是实例图片:

 
  

利用JAVA创建简单的菜单界面_第1张图片

你可能感兴趣的:(Java基础)