Java~Swing中下拉式菜单JMenuBar(菜单栏)、JMenu(菜单)和JMenuItem(菜单项)的使用 |
您所在的位置:网站首页 › 筛选操作用到哪一个菜单中进行 › 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中还有一些常用的方法,如表所示。 由于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 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); } } } } |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |