先附上一张效果图:
(已建窗体JF)
一、基本菜单创建:
(1)一级菜单的建立:
JMenuBar menuBar= new JMenuBar();//创建菜单栏
JF.setJMenuBar(menuBar);//将菜单栏添加到JFrame窗口中
JMenu helpmenu = new JMenu("帮助");//在菜单栏中添加内容
helpmenu.setFont(new Font("宋体",Font.BOLD,20));
helpmenu.setForeground(Color.RED);
menuBar.add(helpmenu);//将菜单添加到菜单栏上
(2)二级菜单的建立:
JMenuItem item = new JMenuItem("关于");
JMenuItem exititem = new JMenuItem("退出");
helpmenu.add(item);
helpmenu.addSeparator();//分割线
helpmenu.add(exititem);
//菜单项事件
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(JF,"提示内容", "提示……",JOptionPane.INFORMATION_MESSAGE);
}
});
(3)若想建第三级菜单,则将第二级也用JMenu定义,第三项用JMenuItem
即:只有最后一项菜单采用JMenuItem定义。
二、设置窗体小图标(图标已事先保存到项目包中)
JF.setIconImage(new ImageIcon("mypicture/logo.jpg").getImage());//设置窗体图标
三、设置窗体背景图(背景图也已事先保存到项目包中)
ImageIcon img1=new ImageIcon("mypicture/background1.jpg");//这里是放置背景图片
JLabel imgLabel01=new JLabel(img1);//将背景图放在标签里//注意这里是关键,将背景图标签添加到JF的LayeredPane面板里
JF.getLayeredPane().add(imgLabel01,new Integer(Integer.MIN_VALUE));
//放置背景标签的位置
imgLabel01.setBounds(120,10,img1.getIconWidth(),img1.getIconHeight());
((JPanel)content).setOpaque(false);
四、窗体中写入文字。
content.add(new JLabel("<html><font size='8' color='blue'>欢 迎 使 用 菜 单 管 理 系 统 1.0 "
+ "</font></html>",JLabel.CENTER),BorderLayout.CENTER);//往面板中添加文字
五、关闭时提示窗口事件。
//以下两个要结合着才能真正的实现提示窗口,否则点任一个按钮均使窗体关闭,而且程序不能真正的关闭
JF.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
JF.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
int option = JOptionPane.showConfirmDialog(null, "您确定关闭吗?",
"关闭提示....",JOptionPane.OK_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE);
if(option == JOptionPane.OK_OPTION){
System.exit(0);
}
}
});