java—如何在jtree中的节点旁边显示特定的属性名称和值?

v2g6jxz6  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(457)

我想在中的节点名称旁边显示属性的名称和值 JTree . 有人能告诉我怎么做吗?下面是我用来显示 JTree :

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Event.*;
import java.io.*;
import javax.swing.tree.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.apache.xerces.parsers.*;

public class XMLTreeView {

    private SAXTreeBuilder saxTree = null;
    private static String file = "";

    public static void main(String args[]) {
        JFrame frame = new JFrame("XMLTreeView: [ games.xml ]");
        frame.setSize(400, 400);

        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent ev) {
                System.exit(0);
            }
        });
        file = "example1.xml";
        new XMLTreeView(frame);
    }

    public XMLTreeView(JFrame frame) {
        frame.getContentPane().setLayout(new BorderLayout());
        DefaultMutableTreeNode top = new DefaultMutableTreeNode(file);
//              DefaultMutableTreeNode top = new DefaultMutableTreeNode("XML Document"); 
        saxTree = new SAXTreeBuilder(top);
        try {
            SAXParser saxParser = new SAXParser();
            saxParser.setContentHandler(saxTree);
            saxParser.parse(new InputSource(new FileInputStream(file)));
        } catch (Exception ex) {
            top.add(new DefaultMutableTreeNode(ex.getMessage()));
        }
        JTree tree = new JTree(saxTree.getTree());
        JScrollPane scrollPane = new JScrollPane(tree);

        frame.getContentPane().add("Center", scrollPane);
        frame.setVisible(true);
    }
}

class SAXTreeBuilder extends DefaultHandler {

    private DefaultMutableTreeNode currentNode = null;
    private DefaultMutableTreeNode previousNode = null;
    private DefaultMutableTreeNode rootNode = null;

    public SAXTreeBuilder(DefaultMutableTreeNode root) {
        rootNode = root;
    }

    public void startDocument() {
        currentNode = rootNode;
    }

    public void endDocument() {
    }

    public void characters(char[] data, int start, int end) {
        String str = new String(data, start, end);
        if (!str.equals("") && Character.isLetter(str.charAt(0))) {
            currentNode.add(new DefaultMutableTreeNode(str));
        }
    }

    public void startElement(String uri, String qName, String lName, Attributes atts) {
        previousNode = currentNode;
        currentNode = new DefaultMutableTreeNode(lName);
        // Add attributes as child nodes //
        attachAttributeList(currentNode, atts);
        previousNode.add(currentNode);
    }

    public void endElement(String uri, String qName, String lName) {
        if (currentNode.getUserObject().equals(lName)) {
            currentNode = (DefaultMutableTreeNode) currentNode.getParent();
        }
    }

    public DefaultMutableTreeNode getTree() {
        return rootNode;
    }

    private void attachAttributeList(DefaultMutableTreeNode node, Attributes atts) {
        for (int i = 0; i < atts.getLength(); i++) {
            String name = atts.getLocalName(i);
            String value = atts.getValue(name);
            node.add(new DefaultMutableTreeNode(name + " = " + value));
        }
    }
}

JTree ,我想显示 NEType 属性旁边 NE 节点,以及 equipmentHolderType 属性旁边 EQHO 节点

NE NEType=WBTS
    EQHO equipmentHolderType=Subrack

我想要这样的东西:

下面是我处理的xml文件示例:

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?> 
<HWData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="hw_data.xsd">
<Header xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" AdaptationName="NWI3BulkUpload" AccessProtocol="NWI3" time="2004-01-01T00:04:02" uploaded="true" version="1.0" /> 
<NE xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" vendorName="Nokia Siemens Networks" objectClass="NE" objectClassVersion="1" MOID="NE-RNC-1/DN:NE-WBTS-4183" NEId="PLMN-PLMN/RNC-1/WBTS-4183" NEType="WBTS" operationalState="enabled" locationName="Tun4183" nameFromPlanningSystem="" systemTitle="Nokia Flexi WCDMA Base Station">
<EQHO vendorName="Nokia Siemens Networks" objectClass="EQHO" objectClassVersion="1" MOID="NE-RNC-1/DN:NE-WBTS-4183/EQHO-40448" equipmentHolderId="40448" equipmentHolderType="Subrack" equipmentHolderSpecificType="472100A-40448" identificationCode="472100A" version="101" serialNumber="K9111641678" userLabel="FRGP" state="working">
<UNIT vendorName="Nokia Siemens Networks" objectClass="UNIT" objectClassVersion="1" MOID="NE-RNC-1/DN:NE-WBTS-4183/EQHO-40448/UNIT-158" unitId="158" unitTypeActual="CORE_FRGP" identificationCode="084629A" version="101" serialNumber="K9111641678" /> 
</EQHO>
<EQHO vendorName="Nokia Siemens Networks" objectClass="EQHO" objectClassVersion="1" MOID="NE-RNC-1/DN:NE-WBTS-4183/EQHO-173" equipmentHolderId="173" equipmentHolderType="Subrack" equipmentHolderSpecificType="471469A-173" identificationCode="471469A" version="" serialNumber="L1104816112" userLabel="FSME" state="working">
<UNIT vendorName="N" objectClass="UNIT" objectClassVersion="1" MOID="NE-RNC-1/DN:NE-WBTS-4183/EQHO-173/UNIT-16" unitId="16" unitTypeActual="CORE_FSME" identificationCode="083833A" version="104" serialNumber="L1104816112" /> 
<UNIT vendorName="NOKIA SIEMENS NETWORKS" objectClass="UNIT" objectClassVersion="1" MOID="NE-RNC-1/DN:NE-WBTS-4183/EQHO-173/UNIT-225" unitId="225" unitTypeActual="FTLB" identificationCode="471984A" version="103" serialNumber="RY104807867" /> 
</EQHO>
<EQHO vendorName="NSN" objectClass="EQHO" objectClassVersion="1" MOID="NE-RNC-1/DN:NE-WBTS-4183/EQHO-40192" equipmentHolderId="40192" equipmentHolderType="Subrack" equipmentHolderSpecificType="472083A-40192" identificationCode="472083A" version="101" serialNumber="L6105220714" userLabel="FXDA" state="working" /> 
</NE>
</HWData>
v9tzhpje

v9tzhpje1#

您可以更改用于构造树节点的字符串:

public void startElement(String uri, String qName, String lName, Attributes atts) {
    previousNode = currentNode;
    // Use the result of the getNodeText method to construct the tree node.
    currentNode = new DefaultMutableTreeNode(getNodeText(lName, atts));
    // Add attributes as child nodes //
    attachAttributeList(currentNode, atts);
    previousNode.add(currentNode);
}

private String getNodeText(final String lName, final Attributes atts) {
    final String postfix;

    if ("NE".equals(lName) && atts.getValue("NEType") != null)
        postfix = " NEType=" + atts.getValue("NEType");
    else if ("EQHO".equals(lName) && atts.getValue("equipmentHolderType") != null)
        postfix = " equipmentHolderType=" + atts.getValue("equipmentHolderType");
    else
        postfix = "";

    return lName + postfix;
}

这是我运行的完整代码:

import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;

public class XMLTreeView {
    private SAXTreeBuilder saxTree = null;
    private static String file = "";

    public static void main(String args[]) {
        file = "etc\\q29921994\\example2.xml";
        JFrame frame = new JFrame("XMLTreeView: [ " + file.substring(file.lastIndexOf("\\") + 1) + " ]");
        frame.setSize(400, 400);

        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent ev) {
                System.exit(0);
            }
        });
        new XMLTreeView(frame);
    }

    public XMLTreeView(JFrame frame) {
        frame.getContentPane().setLayout(new BorderLayout());
        DefaultMutableTreeNode top = new DefaultMutableTreeNode(file);
        //    DefaultMutableTreeNode top = new DefaultMutableTreeNode("XML Document");
        saxTree = new SAXTreeBuilder(top);

        try {
            SAXParser saxParser = new SAXParser();
            saxParser.setContentHandler(saxTree);
            saxParser.parse(new InputSource(new FileInputStream(file)));
        } catch (Exception ex) {
            top.add(new DefaultMutableTreeNode(ex.getMessage()));
        }
        JTree tree = new JTree(saxTree.getTree());
        JScrollPane scrollPane = new JScrollPane(tree);

        frame.getContentPane().add("Center", scrollPane);
        frame.setVisible(true);
    }
}

class SAXTreeBuilder extends DefaultHandler {
    private DefaultMutableTreeNode currentNode = null;
    private DefaultMutableTreeNode previousNode = null;
    private DefaultMutableTreeNode rootNode = null;

    public SAXTreeBuilder(DefaultMutableTreeNode root) {
        rootNode = root;
    }

    public void startDocument() {
        currentNode = rootNode;
    }

    public void endDocument() {
    }

    public void characters(char[] data, int start, int end) {
        String str = new String(data, start, end);
        if (!str.equals("") && Character.isLetter(str.charAt(0)))
            currentNode.add(new DefaultMutableTreeNode(str));
    }

    public void startElement(String uri, String qName, String lName, Attributes atts) {
        previousNode = currentNode;
        // currentNode = new DefaultMutableTreeNode(lName);
        // Use the result of the getNodeText method to construct the tree node.
        currentNode = new DefaultMutableTreeNode(getNodeText(lName, atts));
        // Add attributes as child nodes //
        attachAttributeList(currentNode, atts);
        previousNode.add(currentNode);
    }

    public void endElement(String uri, String qName, String lName) {
        // I think the if below can be removed:
        //if (currentNode.getUserObject().equals(lName))
            currentNode = (DefaultMutableTreeNode) currentNode.getParent();
    }

    private String getNodeText(final String lName, final Attributes atts) {
        final String postfix;

        if ("NE".equals(lName) && atts.getValue("NEType") != null)
            postfix = " NEType=" + atts.getValue("NEType");
        else if ("EQHO".equals(lName) && atts.getValue("equipmentHolderType") != null)
            postfix = " equipmentHolderType=" + atts.getValue("equipmentHolderType");
        else if ("UNIT".equals(lName) && atts.getValue("unitTypeActual") != null)
            postfix = " equipmentHolderType=" + atts.getValue("unitTypeActual");
        else if ("FUUT".equals(lName) && atts.getValue("functionalUnitType") != null)
            postfix = " equipmentHolderType=" + atts.getValue("functionalUnitType");
        else
            postfix = "";

        return lName + postfix;
    }

    public DefaultMutableTreeNode getTree() {
        return rootNode;
    }

    private void attachAttributeList(DefaultMutableTreeNode node, Attributes atts) {
        for (int i = 0; i < atts.getLength(); i++) {
            String name = atts.getLocalName(i);
            String value = atts.getValue(name);
            node.add(new DefaultMutableTreeNode(name + " = " + value));
        }
    }
}

这是我使用的example2.xml文件:

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<HWData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="hw_data.xsd">
    <Header xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" AdaptationName="NWI3BulkUpload" AccessProtocol="NWI3" time="2013-05-29T13:09:29" uploaded="true" version="1.0"/>
    <NE xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" vendorName="Nokia Siemens Networks" objectClass="NE" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204" NEId="PLMN-PLMN/RNC-4/WBTS-4204" NEType="WBTS" operationalState="enabled" locationName="SFX4204" nameFromPlanningSystem="" systemTitle="Nokia Flexi WCDMA Base Station">
        <EQHO vendorName="Nokia Siemens Networks" objectClass="EQHO" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-173" equipmentHolderId="173" equipmentHolderType="Subrack" equipmentHolderSpecificType="471469A-173" identificationCode="471469A" version="" serialNumber="F7123009045" userLabel="FSME" state="working">
            <UNIT vendorName="N" objectClass="UNIT" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-173/UNIT-16" unitId="16" unitTypeActual="CORE_FSME" identificationCode="083833A" version="105" serialNumber="F7123009045"/>
            <UNIT vendorName="NOKIA SIEMENS NETWORKS" objectClass="UNIT" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-173/UNIT-225" unitId="225" unitTypeActual="FTLB" identificationCode="471984A" version="104" serialNumber="K9123412124"/>
        </EQHO>
        <EQHO vendorName="NSN" objectClass="EQHO" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-40192" equipmentHolderId="40192" equipmentHolderType="Subrack" equipmentHolderSpecificType="472083A-40192" identificationCode="472083A" version="203" serialNumber="K9123021259" userLabel="FXDA" state="working">
            <UNIT vendorName="AR" objectClass="UNIT" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-40192/UNIT-56081" unitId="56081" unitTypeActual="TILT" identificationCode="CV3PX310R-BTQ" version="" serialNumber="00000008496310581"/>
            <UNIT vendorName="AR" objectClass="UNIT" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-40192/UNIT-56083" unitId="56083" unitTypeActual="TILT" identificationCode="CV3PX310R-BTQ" version="" serialNumber="00000008496310721"/>
            <UNIT vendorName="AR" objectClass="UNIT" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-40192/UNIT-56085" unitId="56085" unitTypeActual="TILT" identificationCode="CV3PX310R-BTQ" version="" serialNumber="00000008496310441"/>
        </EQHO>
        <EQHO vendorName="AR" objectClass="EQHO" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-56089" equipmentHolderId="56089" equipmentHolderType="Subrack" equipmentHolderSpecificType="CV3PX310R-BTQ-56089" identificationCode="CV3PX310R-BTQ" version="" serialNumber="00000008496310584" userLabel="" state="working"/>
        <EQHO vendorName="AR" objectClass="EQHO" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-56090" equipmentHolderId="56090" equipmentHolderType="Subrack" equipmentHolderSpecificType="CV3PX310R-BTQ-56090" identificationCode="CV3PX310R-BTQ" version="" serialNumber="00000008496310582" userLabel="" state="working"/>
        <EQHO vendorName="AR" objectClass="EQHO" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-56091" equipmentHolderId="56091" equipmentHolderType="Subrack" equipmentHolderSpecificType="CV3PX310R-BTQ-56091" identificationCode="CV3PX310R-BTQ" version="" serialNumber="00000008496310724" userLabel="" state="working"/>
        <EQHO vendorName="AR" objectClass="EQHO" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-56092" equipmentHolderId="56092" equipmentHolderType="Subrack" equipmentHolderSpecificType="CV3PX310R-BTQ-56092" identificationCode="CV3PX310R-BTQ" version="" serialNumber="00000008496310722" userLabel="" state="working"/>
        <EQHO vendorName="AR" objectClass="EQHO" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-56093" equipmentHolderId="56093" equipmentHolderType="Subrack" equipmentHolderSpecificType="CV3PX310R-BTQ-56093" identificationCode="CV3PX310R-BTQ" version="" serialNumber="00000008496310444" userLabel="" state="working"/>
        <EQHO vendorName="AR" objectClass="EQHO" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-56094" equipmentHolderId="56094" equipmentHolderType="Subrack" equipmentHolderSpecificType="CV3PX310R-BTQ-56094" identificationCode="CV3PX310R-BTQ" version="" serialNumber="00000008496310442" userLabel="" state="working"/>
        <EQHO vendorName="Nokia Siemens Networks" objectClass="EQHO" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-40448" equipmentHolderId="40448" equipmentHolderType="Subrack" equipmentHolderSpecificType="472100A-40448" identificationCode="472100A" version="101" serialNumber="K9122905970" userLabel="FRGP" state="working">
            <UNIT vendorName="Nokia Siemens Networks" objectClass="UNIT" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-40448/UNIT-158" unitId="158" unitTypeActual="CORE_FRGP" identificationCode="084629A" version="101" serialNumber="K9122905970"/>
            <UNIT vendorName="AR" objectClass="UNIT" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-40448/UNIT-56593" unitId="56593" unitTypeActual="TILT" identificationCode="CV3PX310R-BTQ" version="" serialNumber="00000008496310583"/>
            <UNIT vendorName="AR" objectClass="UNIT" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-40448/UNIT-56595" unitId="56595" unitTypeActual="TILT" identificationCode="CV3PX310R-BTQ" version="" serialNumber="00000008496310723"/>
            <UNIT vendorName="AR" objectClass="UNIT" objectClassVersion="1" MOID="NE-RNC-4/DN:NE-WBTS-4204/EQHO-40448/UNIT-56597" unitId="56597" unitTypeActual="TILT" identificationCode="CV3PX310R-BTQ" version="" serialNumber="00000008496310443"/>
        </EQHO>
    </NE>
</HWData>

这是运行程序的屏幕截图:

oo7oh9g9

oo7oh9g92#

在下面的变体中,我使用了 javax.xml.parsers ,一个修改的 getNodeText() 以及你的最新 xml .
XMLTreeView.java :

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import javax.swing.tree.*;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**@see http://stackoverflow.com/q/29921994/230513 */
public class XMLTreeView {

    private static final String file = "example.xml";

    public static void main(String args[]) {
        EventQueue.invokeLater(() -> {
            new XMLTreeView();
        });
    }

    public XMLTreeView() {
        JFrame frame = new JFrame("XMLTreeView: [ games.xml ]");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DefaultMutableTreeNode top = new DefaultMutableTreeNode(file);
        SAXTreeBuilder saxTree = new SAXTreeBuilder(top);
        try {
            SAXParserFactory parserFactory = SAXParserFactory.newInstance();
            SAXParser saxParser = parserFactory.newSAXParser();
            saxParser.parse(file, saxTree);
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            ex.printStackTrace(System.err);
        }
        JTree tree = new JTree(saxTree.getTree());
        tree.expandRow(1);
        JScrollPane scrollPane = new JScrollPane(tree);
        frame.add(scrollPane);
        frame.pack();
        frame.setVisible(true);
    }
}

class SAXTreeBuilder extends DefaultHandler {

    private DefaultMutableTreeNode rootNode;
    private DefaultMutableTreeNode currentNode;
    private DefaultMutableTreeNode previousNode;

    public SAXTreeBuilder(DefaultMutableTreeNode root) {
        rootNode = root;
    }

    @Override
    public void startDocument() {
        currentNode = rootNode;
    }

    @Override
    public void startElement(String uri, String qName, String lName, Attributes atts) {
        previousNode = currentNode;
        currentNode = new DefaultMutableTreeNode(getNodeText(lName, atts));
        attachAttributeList(currentNode, atts);
        previousNode.add(currentNode);
    }

    private String getNodeText(final String lName, final Attributes atts) {
        if ("NE".equals(lName)) {
            return lName + " NEType=" + atts.getValue("NEType");
        } else if ("EQHO".equals(lName)) {
            return lName + " equipmentHolderType=" + atts.getValue("equipmentHolderType");
        } else if ("UNIT".equals(lName)) {
            return lName + " equipmentHolderType=" + atts.getValue("unitTypeActual");
        } else if ("FUUT".equals(lName)) {
            return lName + " equipmentHolderType=" + atts.getValue("functionalUnitType");
        } else {
            return lName;
        }
    }

    @Override
    public void endElement(String uri, String qName, String lName) {
        if (currentNode.getUserObject().equals(lName)) {
            currentNode = (DefaultMutableTreeNode) currentNode.getParent();
        }
    }

    public DefaultMutableTreeNode getTree() {
        return rootNode;
    }

    private void attachAttributeList(DefaultMutableTreeNode node, Attributes atts) {
        for (int i = 0; i < atts.getLength(); i++) {
            String name = atts.getLocalName(i);
            String value = atts.getValue(name);
            node.add(new DefaultMutableTreeNode(name + " = " + value));
        }
    }
}
``` `example.xml` :

相关问题