Java~Swing中下拉式菜单JMenuBar(菜单栏)、JMenu(菜单)和JMenuItem(菜单项)的使用

下拉式菜单

  • 在GUI程序中,创建下拉式菜单需要使用三个组件:JMenuBar(菜单栏)、JMenu(单)JMenuItem(菜单项),以记事本为例,这三个组件在菜单中对应的位置如图所示。
    在这里插入图片描述

三个关键组件的介绍

1)JMenuBar:JMenuBar表示一个水平的菜单栏,它用来管理菜单,不参与同用户的交互式操作。菜单栏可以放在容器的任何位置,但通常情况下会使用顶级窗口(如JFrame、JDialog)的setJMenuBar(JMenuBar menuBar)方法将它放置在顶级窗口的顶部。JMenuBar有一个无参构造函数,创建菜单栏时,只需要使用new关键字创建JMenuBar对象即可。创建完菜单栏对象后,可以调用它的add(JMenu c)方法为其添加JMenu菜单。

(2)JMenu:JMenu表示一个菜单,它用来整合管理菜单项。菜单可以是单一层次的结构,也可以是多层次的结构。大多情况下,会使用构造函数JMenu(String text)创建JMenu菜单,其中参数text表示菜单上的文本。JMenu中还有一些常用的方法,如表所示。
在这里插入图片描述
3)JMenuItem:JMenuItem表示一个菜单项,它是菜单系统中最基本的组件。和JMenu菜单一样,在创建JMenuItem菜单项时,通常会使用构造方法JMenumItem(String text)为菜单项指定文本内容。

由于JMenuItem类是继承自AbstractButton类的,因此可以把它看成是一个按钮。如果使用无参的构造方法创建了一个菜单项,则可以调用从AbstractButton类中继承的setText(String text)方法和setIcon()方法为其设置文本和图标。

代码演示

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class MenuTest extends JFrame implements ActionListener
{
    
    
	private JButton redBt,greenBt,blueBt;
	
	//定义菜单有关的一些对象
	JMenuBar menuBar;//菜单栏
	JMenu colorMenu;//设置窗体背景颜色的菜单
	JMenuItem[] colorMenuItems;//设置窗体背景颜色的菜单项数组
	
	
	private void initButton()
	//初始化按钮的方法
	{
    
    
		this.setLayout(null);
		redBt = new JButton("红色");
		redBt.setSize(60, 30);
		redBt.setLocation(30, 30);
		this.add(redBt);
		greenBt = new JButton("绿色");
		greenBt.setSize(60, 30);
		greenBt.setLocation(120, 30);
		this.add(greenBt);
		blueBt = new JButton("蓝色");
		blueBt.setSize(60, 30);
		blueBt.setLocation(210, 30);
		this.add(blueBt);
		
		redBt.addActionListener(this);
		greenBt.addActionListener(this);
		blueBt.addActionListener(this);
	}
	
	//初始化菜单的方法
	private void initMenu()
	{
    
    
		colorMenu=new JMenu("设置窗体背景");
		String[] colors={
    
    "红色","绿色","蓝色"};
		colorMenuItems=new JMenuItem[3];
		//定义一个包含3个菜单项的数组
		for(int i=0;i<3;i++)
		{
    
    
			colorMenuItems[i]=new JMenuItem(colors[i]);
			//初始化每个菜单项,给菜单项进行文本的赋值
			colorMenuItems[i].addActionListener(this);
			//注册事件源菜单项和事件处理对象
			colorMenu.add(colorMenuItems[i]);
			//以菜单为对象,调用方法来添加菜单所包含的菜单项
		}
		menuBar=new JMenuBar();//初始化菜单栏
		menuBar.add(colorMenu);//将菜单添加到菜单栏上
		this.setJMenuBar(menuBar);
		//以窗体为对象,调用方法来设置窗体的菜单栏
	}
	
	public MenuTest()
	{
    
    
		this.setSize(300, 300);
		this.setTitle("菜单实例");
		initMenu();
		initButton();
		this.setVisible(true);
	}

	public void actionPerformed(ActionEvent e) 
	{
    
    
		AbstractButton item=(AbstractButton)e.getSource();
		//将动作事件的事件源强制转换为抽象的按钮对象
		if(item.getText().equals("红色"))
		{
    
    
			this.getContentPane().setBackground(Color.red);
		}
		else
		{
    
    
			if(item.getText().equals("绿色"))
			{
    
    
				this.getContentPane().setBackground(Color.green);
			}
			else
			{
    
    
				this.getContentPane().setBackground(Color.blue);
			}
		}
		
	}
}

猜你喜欢

转载自blog.csdn.net/Shangxingya/article/details/108438551