补充,因为没处理好这个ButtonGroup问题,结果菜单上出现2只“眼睛”

解决方案 »

  1.   

    还是用JDOM,代码精简,如下即可,测试通过==============================================================================
    import org.jdom.*;import org.jdom.output.*;import org.jdom.input.*;import java.io.*;public class TestJDOM{    public static void main(String args[])throws Exception{                SAXBuilder sb = new SAXBuilder();         //´ÓÎļþ¹¹ÔìÒ»¸öDocument£¬ÒòΪXMLÎļþÖÐÒѾ­Ö¸¶¨Á˱àÂ룬ËùÒÔÕâÀï²»±ØÁË        Document doc = sb.build(new FileInputStream("exampleA.xml"));                //¼ÓÈëÒ»Ìõ´¦ÀíÖ¸Áî        ProcessingInstruction pi = new ProcessingInstruction            ("xml-stylesheet","href=\"bookList.html.xsl\" type=\"text/xsl\"");        doc.addContent(pi);          Element root = doc.getRootElement(); //µÃµ½¸ùÔªËØ        java.util.List books = root.getChildren(); //µÃµ½¸ùÔªËØËùÓÐ×ÓÔªËصļ¯ºÏ        Element book = (Element)books.get(0); //µÃµ½µÚÒ»¸öbookÔªËØ        //ΪµÚÒ»±¾ÊéÌí¼ÓÒ»ÌõÊôÐÔ        Attribute a = new Attribute("hot","true");          book.setAttribute(a);        Element author = book.getChild("author"); //µÃµ½Ö¸¶¨µÄ×ÖÔªËØ        author.setText("ÍõÎå"); //½«×÷Õ߸ÄΪÍõÎå        //»ò Text t = new Text("ÍõÎå");book.addContent(t);        Element price = book.getChild("price"); //µÃµ½Ö¸¶¨µÄ×ÖÔªËØ        //Ð޸ļ۸ñ£¬±È½ÏÓôÃƵÄÊÇÎÒÃDZØÐë×Ô¼º×ª»»Êý¾ÝÀàÐÍ£¬¶øÕâÕýÊÇJAXBµÄÓÅÊÆ        price.setText(Float.toString(50.0f));                   String indent = "    ";        boolean newLines = true;        XMLOutputter outp = new XMLOutputter(indent,newLines,"GBK");        outp.output(doc, new FileOutputStream("exampleB.xml"));     }}==============================================================================
      

  2.   

    yultao(何弦) 感谢你的回贴,但是我问的是怎么由我的这个xml文件解析出正确的菜单,不是普通的怎样解析xml文件的问题。输出的结果应该是JMenuBar,并且能正确的解析出其中的Radio类型的菜单。
    用什么解析都没关系,只要能解析出来菜单即可。
    其中涉及到一个与递归有关的算法。
      

  3.   

    等你这一切都做完后,再来一次地鬼把所有的Radio加到适当的得ButtonGroup不就行了吗?
      

  4.   

    to maowu(猫呜) ( ) 
    搞完了再另外设置GroupButton就不好了,你根据什么再组织这些GroupButton呢?
    用设计的观点来看。 这样势必跟具体的业务逻辑关联起来。这样就不是一个通用的组件了。
    这样就象JDK Demo·SwingSet2里代码一样,眉毛胡子都搅到一起,乱成一锅粥了。
    而xml文件里是写得很清楚的,哪些应该为一组。我已经自行解决:将GroupButton作为递归函数里的一个参数即可。狂散分!想要分的进来
      

  5.   

    下面是解析过程的完整代码:import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.lang.reflect.Constructor;
    import java.util.HashMap;
    import java.util.Map;import javax.swing.Action;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.KeyStroke;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;/**
     * A Common menu xml parser.
     * @author usabcd
     */
    public class MenuXmlParser {    private static JMenuBar menuBar = new JMenuBar();
        private static String packageName = "";
        private InputStream is;
        private MainPanel mp;
        private Map modifiers = new HashMap();    public MenuXmlParser(String uri) {
            try {
                is = MenuXmlParser.class.getResourceAsStream(uri);
            } catch (Exception e) {
                //log.error("", e);
                e.printStackTrace();
            }
        }    public MenuXmlParser(File file) {
            InputStream is = null;
            try {
                is = new FileInputStream(file);
            } catch (Exception e) {
                //log.error("", e);
                e.printStackTrace();
            }
        }    public MenuXmlParser(InputStream is) {
            this.is = is;
        }    public void setMainPanel(MainPanel mp) {
            this.mp = mp;
        }    public void parseXml() {        modifiers.put("CTRL", new Integer(2));
            modifiers.put("ALT", new Integer(8));
            modifiers.put("META", new Integer(4));
            modifiers.put("SHIFT", new Integer(1));        try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                //dbf.setIgnoringElementContentWhitespace(false);
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = null;
                doc = db.parse(is);
                Element e0 = doc.getDocumentElement();
                packageName = e0.getAttribute("package");            NodeList nl = e0.getChildNodes();            for (int i = 0; i < nl.getLength(); i++) {
                    Node n = nl.item(i);
                    if (n.getNodeType() == Node.ELEMENT_NODE) {
                        Element e1 = (Element) n;
                        JMenu menu = (JMenu) menuBar.add(new JMenu(e1.getAttribute("label")));
                        menu.getAccessibleContext().setAccessibleDescription(
                            e1.getAttribute("description"));
                        createJMenu(menu, e1, new ButtonGroup());
                    }
                }        } catch (Exception e) {
                //log.error("", e);
                e.printStackTrace();
            }
        }    private void createJMenu(JMenu menu, Element e0, ButtonGroup bg) {
            JMenuItem mi = null;
            NodeList nl = e0.getChildNodes();
            for (int i = 0; i < nl.getLength(); i++) {
                Node n = nl.item(i);
                if (n.getNodeType() == Node.ELEMENT_NODE) {
                    Element e1 = (Element) n;                String type = e1.getAttribute("type");
                    String label = e1.getAttribute("label");                if ("popup".equals(type)) {                    JMenu popupMenu = (JMenu) menu.add(new JMenu(label));
                        createJMenu(popupMenu, e1, new ButtonGroup());
                    } else if ("separator".equals(type)) {
                        menu.addSeparator();
                    } else {
                        String action = e1.getAttribute("action");
                        String mnemonic = e1.getAttribute("mnemonic");
                        String accelerator = e1.getAttribute("accelerator");
                        String mask = e1.getAttribute("mask");
                        String description = e1.getAttribute("description");
                        if ("radio".equals(type)) {
                            mi =
                                (JRadioButtonMenuItem) menu.add(
                                    new JRadioButtonMenuItem(label));
                            String selected = e1.getAttribute("selected");
                            if ("true".equals(selected)) {
                                mi.setSelected(true);
                            }
                            bg.add(mi);
                        } else {
                            mi = (JMenuItem) menu.add(new JMenuItem(label));
                        }
                        if (mnemonic != null && mnemonic.length() == 1) {
                            mi.setMnemonic(mnemonic.charAt(0));
                        }
                        mi.getAccessibleContext().setAccessibleDescription(description);
                        if (accelerator != null && !accelerator.equals("")) {
                            Character c = new Character(accelerator.charAt(0));
                            KeyStroke ks = KeyStroke.getKeyStroke(c, getModifiers(mask));
                            mi.setAccelerator(ks);
                        }
                        if (action == null || action.equals("")) {
                            mi.setEnabled(false);
                            continue;
                        }
                        Action a = null;
                        try {
                            action = packageName + "." + action;
                            Class clazz = Class.forName(action);
                            Class[] parameterTypes = { MainPanel.class, String.class };
                            Constructor c = clazz.getConstructor(parameterTypes);
                            a = (Action) c.newInstance(new Object[] { mp, mnemonic });
                        } catch (Exception e) {
                            //log.error("", e);
                            e.printStackTrace();
                        }
                        mi.addActionListener(a);
                        if (a == null) {
                            mi.setEnabled(false);
                        }                }
                }
            }
        }    /**
         * Get a localized string depends on the system locale type.
         * @param key
         * @return a string value.
         */
        public JMenuBar getJMenuBar() {
            return menuBar;
        }    public static void main(String[] args) throws Exception {
            String uri = "/com/test/proj/client/swing/menu_zh_CN.xml";
            MenuXmlParser mxp = new MenuXmlParser(uri);
            mxp.parseXml();
            for (int i = 0; i < menuBar.getMenuCount(); i++) {
                JMenu menu = menuBar.getMenu(i);
                printMenu(menu);
            }
        }    static int indent = 1;    private static void printMenu(JMenu menu) {
            indent++;
            System.out.println(repeat(" ", (indent - 1) * 2) + menu.getText());
            for (int j = 0; j < menu.getItemCount(); j++) {
                JMenuItem mi = menu.getItem(j);
                if (mi instanceof JMenu) {
                    printMenu((JMenu) mi);
                } else if (mi != null) {
                    String ls = repeat(" ", indent * 2);
                    KeyStroke ks = mi.getAccelerator();
                    String a = ks == null ? "" : ks.toString();
                    System.out.println(ls + mi.getText() + " " + a);
                }
            }
            indent--;
        }    private static String repeat(String s, int cnt) {
            String result = "";
            for (int i = 0; i < cnt; i++) {
                result += s;
            }
            return result;
        }    private int getModifiers(String allMask) {
            int mod = 0;
            String[] masks = allMask.split("\\+");
            for (int i = 0; i < masks.length; i++) {
                mod += ((Integer) modifiers.get(masks[i])).intValue();
            }
            return mod;
        }
    }
      

  6.   

    这是菜单内容:<?xml version="1.0" encoding="GB2312" ?>
    <menu package="com.test.proj.client.swing.action">
        <menu label="文件" mnemonic="F" description="" package="">
            <menu label="关于(B)" mnemonic="B" action="AboutAction" decription=""/>
            <menu type="separator"/>
            <menu label="打开(O)" mnemonic="O" action="" accelerator="O" mask="CTRL" decription=""/>
            <menu label="保存(S)" mnemonic="S" action="" accelerator="S" mask="CTRL" decription=""/>
            <menu label="另存为(A)..." mnemonic="A" action=""  accelerator="A" mask="CTRL" decription=""/>
            <menu type="separator"/>
            <menu label="退出(X)" mnemonic="X"  accelerator="X" mask="CTRL" action="ExitAction" decription=""/>
        </menu>
        <menu label="外观感觉" mnemonic="L" description="" package="">
            <menu type="radio" label="Java" mnemonic="J" selected="true" action="ChangeLookAndFeelAction" decription=""/>
            <menu type="radio" label="Mac" mnemonic="M" action="ChangeLookAndFeelAction" decription=""/>
            <menu type="radio" label="Motif" mnemonic="O" action="ChangeLookAndFeelAction" decription=""/>
            <menu type="radio" label="Windows" mnemonic="W" action="ChangeLookAndFeelAction" decription=""/>
            <menu type="radio" label="GTK" mnemonic="G" action="ChangeLookAndFeelAction" decription=""/>
        </menu>
        <menu label="Theme" mnemonic="S" description="" package="">
            <menu type="popup" label="Audio" mnemonic="A" decription="" package="">
                <menu type="radio" label="On" mnemonic="N" action="OnAudioAction" decription=""/>
                <menu type="radio" label="Default" mnemonic="D" selected="true" action="DefaultAudioAction" decription=""/>
                <menu type="radio" label="Off" mnemonic="F" action="OffAudioAction" decription=""/>
            </menu>
            <menu type="radio" label="Default" mnemonic="D" action="ChangeThemeAction" decription=""/>
            <menu type="radio" label="Aqua" mnemonic="A" action="ChangeThemeAction" decription=""/>
            <menu type="radio" label="Charcoal" mnemonic="C" action="ChangeThemeAction" decription=""/>
            <menu type="radio" label="Contrast" mnemonic="T" action="ChangeThemeAction" decription=""/>
            <menu type="radio" label="Emerald" mnemonic="E" action="ChangeThemeAction" decription=""/>
            <menu type="radio" label="Ruby" mnemonic="R" action="ChangeThemeAction" decription=""/>
        </menu>
        <menu label="ToolTip" mnemonic="T">
            <menu type="radio" label="On" mnemonic="T" action="ToolTipAction"/>
            <menu type="radio" label="Off" mnemonic="F" action="ToolTipAction"/>
        </menu>
    </menu>