对于正在学习java界面编程的小伙伴们,多会到菜单栏编程这一步,对于菜单栏的编程涉及到至少五个java的类,下面小编给出介绍。
工具/原料
eclipse软件
win7系统
1(3)准备
1、1.打开ied也就是打开自己的eclipse软件,当然也可以使用不同的IED,第一步就是打开它。
2、2.建立一个java工程建立工程,是编写一个java项目的第一步,相信大家刚开始学习java的时候都已经会了吧。
2(3)主类编程
1、1.主类模型经分析,主类需要建立一个窗口类;需要有面板,按钮,菜单栏,菜单项等对象;同时,还需要事件处理类;构造方法、事件处理方法、main方法;具体代码如下:package textmenu;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;public class textmenu extends JFrame implements ActionListener{ private static final int DEFAULT_WIDTH=300; private static final int DEFAULT_HEIGHT=300; private JLabel label=new JLabel(); private JMenuItem openItem =new JMenuItem("打开"); private JMenuItem exitItem =new JMenuItem("关闭"); public textmenu(){ } public void actionPerformed(ActionEvent e){ } public static void main(String[] args) { }}
2、2.建立构造方法所谓构造方法就是实现对象实例化的一个方法,用于对实例化的对象进行初始化处理;代码如下:public textmenu(){ setTitle("看图片"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); add(label); JMenuBar menuBar=new JMenuBar(); setJMenuBar(menuBar); JMenu menu=new JMenu("文件"); menuBar.add(menu); menu.add(openItem); openItem.addActionListener(this); menu.add(exitItem); exitItem.addActionListener(this); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); }
3、3.事件处理方法鼠标每动一次就会触发一个事件,该方法就是这个事件进行相关的相应,本实例的代码如下: public void actionPerformed(ActionEvent e){ if(e.getSource()==openItem){ } if(e.getSource()==exitItem){ System.exit(0); } }
4、4.建立main方法对于所有的java工程或是类,main方法都是程序执行的入口,若没有则无法运行。代码如下: public static void main(String[] args) { new textmenu(); }
3(3)验证效果
1、1.编译运行和其他的java工程一样,单击“编译运行”按钮,或是通过菜单栏中找到这个命令就可以了,会出现初始化以后的界面。
2、2.操作验证我们尝试一下对菜单栏进行选择,试试。
3、3总结:本工程的全部代码粘贴如下:package textmenu;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;public class textmenu extends JFrame implements ActionListener{ private static final int DEFAULT_WIDTH=300; private static final int DEFAULT_HEIGHT=300; private JLabel label=new JLabel(); private JMenuItem openItem =new JMenuItem("打开"); private JMenuItem exitItem =new JMenuItem("关闭"); public textmenu(){ setTitle("看图片"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); add(label); JMenuBar menuBar=new JMenuBar(); setJMenuBar(menuBar); JMenu menu=new JMenu("文件"); menuBar.add(menu); menu.add(openItem); openItem.addActionListener(this); menu.add(exitItem); exitItem.addActionListener(this); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } public void actionPerformed(ActionEvent e){ if(e.getSource()==openItem){ } if(e.getSource()==exitItem){ System.exit(0); } } public static void main(String[] args) { new textmenu(); }}