GUI_多级菜单案例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/L1585931143/article/details/68946716
package cn.itcast_09;

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;
import java.io.IOException;

/*
 * 多级菜单
 */
public class FrameDemo {
	public static void main(String[] args) {
		// 创建窗体对象设置属性及布局
		final Frame f = new Frame("多级菜单");
		f.setBounds(400, 200, 400, 300);
		f.setLayout(new FlowLayout());
		final String name = f.getTitle();

		// 创建菜单栏
		MenuBar mb = new MenuBar();
		// 创建菜单
		Menu m1 = new Menu("文件");
		// 创建二级菜单
		Menu m2 = new Menu("更改名称");
		// 创建菜单项
		final MenuItem mi1 = new MenuItem("好好学习");
		final MenuItem mi2 = new MenuItem("天天向上");
		final MenuItem mi3 = new MenuItem("恢复标题");
		MenuItem mi4 = new MenuItem("打开记事本");
		MenuItem mi5 = new MenuItem("退出系统");

		// 添加菜单组件
		m2.add(mi1);
		m2.add(mi2);
		m2.add(mi3);

		m1.add(m2);
		m1.add(mi4);
		m1.add(mi5);

		mb.add(m1);
		f.setMenuBar(mb);

		// 设置关闭窗体
		f.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

		// 好好学习
		mi1.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				f.setTitle(mi1.getLabel());
			}
		});

		// 天天向上
		mi2.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				f.setTitle(mi2.getLabel());
			}
		});

		// 恢复标题
		mi3.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				f.setTitle(name);
			}

		});

		// 打开记事本
		mi4.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				Runtime r = Runtime.getRuntime();
				try {
					r.exec("notepad");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});

		// 退出系统并闭记事本
		mi5.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				Runtime r = Runtime.getRuntime();
				try {
					r.exec("taskkill /f /im notepad.exe");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				System.exit(0);
			}
		});

		// 设置窗体可见
		f.setVisible(true);
	}
}

展开阅读全文

没有更多推荐了,返回首页