一、 制作一个可用的菜单系统,一般需要经过下面几个步骤
Step 1创建一个JMenuBar对象并将其放置在一个JFrame中
Step 2创建JMenu对象
Step 3创建JMenuItem对象并将其添加到JMenu对象中
Step 4把JMenu对象添加到JMenuBar中
上面这几步主要是创建菜单的结构,如果要使用菜单所指出的功能,则必须要为菜单项注册监听者,并在监听者提供的事件处 理程序中写入相应的代码。
二、代码实现
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class MainFrame1 extends JFrame
{
Container container;
public MainFrame1()
{
this.setTitle("测试菜单栏");
container = this.getContentPane();
container.setLayout(new BorderLayout());
JMenuBar menuBar = new JMenuBar();
buildMainMenu(menuBar);
this.setJMenuBar(menuBar);
this.setVisible(true);
this.setSize(600,450);
}
protected void buildMainMenu(JMenuBar menuBar)
{
JMenu fileMenu = new JMenu("文件(F)");//第一个菜单
JMenuItem exitMenuItem = new JMenuItem("退出");
exitMenuItem.addActionListener(new ExitActionListener());
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
JMenu libMenu = new JMenu("馆藏检索(B)");//第二个菜单
libMenu.setMnemonic(KeyEvent.VK_B);//给菜单定义助记键
JMenuItem libMenuItem = new JMenuItem("书目检索");
JMenuItem myBorrowMenuItem = new JMenuItem("我的借阅");
libMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,ActionEvent.CTRL_MASK));//设定快捷键
libMenuItem.addActionListener(new BookInLibraryActionListener());
myBorrowMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M,ActionEvent.CTRL_MASK));//设定快捷键
myBorrowMenuItem.addActionListener(new MyBorrowActionListener());
libMenu.add(libMenuItem);
libMenu.add(myBorrowMenuItem);
menuBar.add(libMenu);
JMenu helpMenu = new JMenu("帮助(H)");//第三个菜单
helpMenu.setMnemonic(KeyEvent.VK_H);
JMenuItem aboutMenuItem = new JMenuItem("关于");
aboutMenuItem.setMnemonic(KeyEvent.VK_A);
aboutMenuItem.addActionListener(new AboutActionListener());
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
}
class BookInLibraryActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
new JComboBoxDemo();
}
}
class MyBorrowActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
new JRadioButtonDemo();
}
}
class AboutActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String msg = "图书管理系统V1.0\nCopyright(C)2014\n\nBy zhouzixin";
String title = "图书管理系统";
JOptionPane.showMessageDialog(container, msg,title,JOptionPane.INFORMATION_MESSAGE);
}
}
class ExitActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
dispose();
System.exit(0);
}
}
public static void main(String[] args)
{
new MainFrame1();
}
}
三、效果展示