运行效果:
示例代码:
package 高级Swing组件之菜单应用; import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButton; public class MenuTest extends JFrame { public static void main(String[] args) { MenuTest tf=new MenuTest(); tf.showUI(); } /** * 显示一个家有多个组件的窗体界面 */ private void showUI() { // TODO Auto-generated method stub this.setTitle("菜单添加示例"); FlowLayout f1=new FlowLayout(); this.setLayout(f1); this.setSize(200, 100); this.setLocation(500, 300); this.setDefaultCloseOperation(3); this.setJMenuBar(createMB()); this.setVisible(true); } /** * 创建一个带有菜单的菜单条 * @return */ private JMenuBar createMB() { // TODO Auto-generated method stub //创建菜单条 JMenuBar mb=new JMenuBar(); //创建文件菜单 JMenu m_file=new JMenu("文件"); //创建文件菜单下的菜单项 JMenuItem mi_open=new JMenuItem("打开"); JMenuItem mi_new=new JMenuItem("新建"); JMenuItem mi_exit=new JMenuItem("退出"); //将菜单项加到文件菜单上 m_file.add(mi_open); m_file.add(mi_new); m_file.add(mi_exit); //创建功能菜单 JMenu m_oper=new JMenu("数据管理"); //创建功能菜单下的菜单项 JMenuItem mi_add=new JMenuItem("新增"); JMenuItem mi_modi=new JMenuItem("修改"); JMenuItem mi_delete=new JMenuItem("删除"); JRadioButton mi_radi=new JRadioButton("总在最前"); JMenuItem mi_about=new JMenuItem("关于"); //将上述菜单项加到功能菜单上的 m_oper.add(mi_add); m_oper.add(mi_modi); m_oper.add(mi_delete); m_oper.add(mi_about); m_oper.addSeparator();//加上一个分割条 m_oper.add(mi_radi); //将文件和功能菜单加到菜单条上 mb.add(m_file); mb.add(m_oper); return mb; } }