需要做一个菜单,其中包含有2个子菜单
而第二个子菜单的子菜单是不确定的,需要每次显示菜单前,根据一个文件的内容 来生成!应该如何来实现呢?

解决方案 »

  1.   

    /*
     * SampleMenu.java
     *
     * Created on 2005年7月8日, 上午9:36
     *//**
     *
     * @author  Administrator
     */
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    //import com.incors.plaf.alloy.*;
    //import com.incors.plaf.alloy.themes.glass.*;public class SampleMenu extends JFrame{ JTextArea theArea = null; public SampleMenu(){
      
      super("JMenu1");
      theArea = new JTextArea();
      theArea.setEditable(true);
      getContentPane().add(new JScrollPane(theArea));
      JMenuBar MBar = new JMenuBar();
      
      JMenu mfile = buildFileMenu();   MBar.add(mfile);  
      setJMenuBar(MBar);
    }//end of JMenu1() public JMenu buildFileMenu() {
      
      JMenu thefile = new JMenu("文件");
      JMenuItem newf=new JMenuItem("新建");
      JMenuItem open=new JMenuItem("打开");
      JMenuItem close=new JMenuItem("关闭");
      JMenuItem exit2=new JMenuItem("退出2");
              
              
              JMenu exit=new JMenu("退出");
              
              
              JMenuItem exit1=new JMenuItem("退出1");
              exit.add(exit1);
      System.out.println("dffsf");
          thefile.add(newf);
          thefile.add(open);
          thefile.add(close);
          thefile.addSeparator();//分隔线
          thefile.add(exit);
          
          exit.add(exit2);
      return thefile;
    }//end of buildFileMenu()
    public static void main(String[] args){
          SwingUtil.setLookAndFeel();
      JFrame F = new SampleMenu();
      F.setSize(400,200);
      F.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          System.exit(0); 
        }
      });//end of addWindowListener
      F.setVisible(true); 
    } // end of main
    }//end of class JMenu1
    class SwingUtil{
      public static final void setLookAndFeel() {
       try{
                Font font = new Font("JFrame", Font.PLAIN, 12);
                Enumeration keys = UIManager.getLookAndFeelDefaults().keys();
     
                while (keys.hasMoreElements()) {
                   Object key = keys.nextElement();
                   if (UIManager.get(key) instanceof Font) {
                      UIManager.put(key, font);
                    }
                } 
             //AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true");
             //AlloyTheme theme = new GlassTheme();
             //LookAndFeel alloyLnF = new AlloyLookAndFeel(theme);
               // UIManager.setLookAndFeel(alloyLnF);
       }catch(Exception ex){
         ex.printStackTrace();
       }
     }
    }
      

  2.   

    在建议“退出1”和“退出2”之间console会输出信息,表示菜单可以在不同时间加入