XML in a JTree

How can i show an XML Document in a JTree
plz help

I'm working on this. Take a look here
http://dotuseful.sourceforge.net/doc/tutorials/automateddomtree/automateddomtree.htm
Denis Krukovsky
http://dotuseful.sourceforge.net/

Similar Messages

  • Is it possible to reprent XML in a JTree format?

    Hi
    I have an XML file.I want to retrieve all the nodes in my XML file and put it in a JTree..Is it possible to do??If so how we can go about this???
    thanks for your reply in advance

    Since XML is naturally a tree then all you need to do is write a tree model that maps onto a DOM model. I do this using JDOM.
    It does not take much code to just create a viewer but it takes quite a lot of code if you want to edit the tree. I am working on this edit feature at the moment.
    I use a renderer that uses a mapping file (also in XML) in order to define how a node should be rendered. This feature is significantly more complex than simple rendering but is very efective and it means I separate the model from the view.

  • How to Create XML Schema From JTree ?

    Please help me... Thank you.
    This is Code
    Tree.java ----- Run This File
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Tree extends JPanel implements ActionListener {
        private int newNodeSuffix = 1;
        private static String ADD_COMMAND = "add";
        private static String REMOVE_COMMAND = "remove";
        private static String CLEAR_COMMAND = "clear";
        private static String OK_COMMAND = "ok";
        private DynamicTree treePanel;
        public Tree() {
            super(new BorderLayout());
            //Create the components.
            treePanel = new DynamicTree();
            //populateTree(treePanel);
            JButton addButton = new JButton("Add");
            addButton.setActionCommand(ADD_COMMAND);
            addButton.addActionListener(this);
            JButton removeButton = new JButton("Remove");
            removeButton.setActionCommand(REMOVE_COMMAND);
            removeButton.addActionListener(this);
            JButton clearButton = new JButton("Clear");
            clearButton.setActionCommand(CLEAR_COMMAND);
            clearButton.addActionListener(this);
            JButton okButton = new JButton("OK");
            okButton.setActionCommand(OK_COMMAND);
            okButton.addActionListener(this);
            //Lay everything out.
            treePanel.setPreferredSize(new Dimension(300, 150));
            add(treePanel, BorderLayout.CENTER);
            JPanel panel = new JPanel(new GridLayout(0,1));
            panel.add(addButton);
            panel.add(removeButton);
            panel.add(clearButton);
            panel.add(okButton);
            add(panel, BorderLayout.LINE_END);
        /*public void populateTree(DynamicTree treePanel) {
            String p1Name = new String("Parent 1");
            //String p2Name = new String("Parent 2");
            String c1Name = new String("Child 1");
            //String c2Name = new String("Child 2");
            DefaultMutableTreeNode p1;
            p1 = treePanel.addObject(null, p1Name);
            //p2 = treePanel.addObject(null, p2Name);
            treePanel.addObject(p1, c1Name);
            //treePanel.addObject(p1, c2Name);
            //treePanel.addObject(p2, c1Name);
            //treePanel.addObject(p2, c2Name);
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
            if (ADD_COMMAND.equals(command)) {
                //Add button clicked.
                treePanel.addObject("New Node " + newNodeSuffix++);
            } else if (REMOVE_COMMAND.equals(command)) {
                //Remove button clicked.
                treePanel.removeCurrentNode();
            } else if (CLEAR_COMMAND.equals(command)) {
                //Clear button clicked.
                treePanel.clear();
            } else if (OK_COMMAND.equals(command)) {
                 //Ok button clicked.
                 treePanel.ok();
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("Craete XML Tree");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            Tree newContentPane = new Tree();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }DynamicTree.java
    import javax.swing.JOptionPane;
    import java.awt.GridLayout;
    import java.awt.Toolkit;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.MutableTreeNode;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    public class DynamicTree extends JPanel {
        protected DefaultMutableTreeNode rootNode;
        protected DefaultTreeModel treeModel;
        protected JTree tree;
        private Toolkit toolkit = Toolkit.getDefaultToolkit();
        public DynamicTree() {
            super(new GridLayout(1,0));
            rootNode = new DefaultMutableTreeNode("Root Node");
            treeModel = new DefaultTreeModel(rootNode);
            treeModel.addTreeModelListener(new MyTreeModelListener());
            tree = new JTree(treeModel);
            tree.setEditable(true);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(true);
            JScrollPane scrollPane = new JScrollPane(tree);
            add(scrollPane);
        /** Remove all nodes except the root node. */
        public void clear() {
            rootNode.removeAllChildren();
            treeModel.reload();
        public void ok() {
             int n = JOptionPane.showConfirmDialog(null, "Do you want to create XML Schema?", "", JOptionPane.YES_NO_OPTION);
        /** Remove the currently selected node. */
        public void removeCurrentNode() {
            TreePath currentSelection = tree.getSelectionPath();
            if (currentSelection != null) {
                DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)
                             (currentSelection.getLastPathComponent());
                MutableTreeNode parent = (MutableTreeNode)(currentNode.getParent());
                if (parent != null) {
                    treeModel.removeNodeFromParent(currentNode);
                    return;
            // Either there was no selection, or the root was selected.
            toolkit.beep();
        /** Add child to the currently selected node. */
        public DefaultMutableTreeNode addObject(Object child) {
            DefaultMutableTreeNode parentNode = null;
            TreePath parentPath = tree.getSelectionPath();
            if (parentPath == null) {
                parentNode = rootNode;
            } else {
                parentNode = (DefaultMutableTreeNode)
                             (parentPath.getLastPathComponent());
            return addObject(parentNode, child, true);
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child) {
            return addObject(parent, child, false);
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child,
                                                boolean shouldBeVisible) {
            DefaultMutableTreeNode childNode =
                    new DefaultMutableTreeNode(child);
            if (parent == null) {
                parent = rootNode;
            treeModel.insertNodeInto(childNode, parent,
                                     parent.getChildCount());
            //Make sure the user can see the lovely new node.
            if (shouldBeVisible) {
                tree.scrollPathToVisible(new TreePath(childNode.getPath()));
            return childNode;
        class MyTreeModelListener implements TreeModelListener {
            public void treeNodesChanged(TreeModelEvent e) {
                DefaultMutableTreeNode node;
                node = (DefaultMutableTreeNode)
                         (e.getTreePath().getLastPathComponent());
                 * If the event lists children, then the changed
                 * node is the child of the node we've already
                 * gotten.  Otherwise, the changed node and the
                 * specified node are the same.
                try {
                    int index = e.getChildIndices()[0];
                    node = (DefaultMutableTreeNode)
                           (node.getChildAt(index));
                } catch (NullPointerException exc) {}
                System.out.println("The user has finished editing the node.");
                System.out.println("New value: " + node.getUserObject());
            public void treeNodesInserted(TreeModelEvent e) {
            public void treeNodesRemoved(TreeModelEvent e) {
            public void treeStructureChanged(TreeModelEvent e) {
    }

    XML shema is basically an XML file. So u need to know how to create an XML,
    provided u know how the shema file should be.
    Creating an XML :
    http://forum.java.sun.com/thread.jspa?threadID=5181031&messageID=9705786#9705786

  • JDom + XML (nested tags) + JTree (Swing)

    I have an XML file that looks like this:
    <root>
      <subtree>
        <a name="John Doe">Here is one big string with information about john doe</a>
        <a name="Tom Smith">Another string</a>
      </subtree>
      <subtree>
        <subtree>
            <a name="abc">mlsjkfqm</a>
        </subtree>
        <subtree>
            <a name="def">qsmdlfkj</a>
             <subtree>
                <a name="ghi">mqsldjkf</a>
                <a name="jkl">mqlsdfjkq</a>
             </subtree>
        </subtree>
      </subtree>
    </root>I want to have this XML file viewed in a JTree. I was told I should use a JTreeModel to store the data in, and org.JDom to parse the data and put them in the JTreeModel. But I still don't see how...
    Can anyone please put me in the right direction, or give some examples of similar examples?
    (I found examples on the web, but they all use trees like <root><node>qsdf</node><node>qsfqsdf</node><node>...</node></root>, so no nested nodes, and I have a difference between <subtree> and <a>...)
    Thanks in advance!

    I want to have this XML file viewed in a JTree. I was
    told I should use a JTreeModel to store the data in,
    and org.JDom to parse the data and put them in the
    JTreeModel. But I still don't see how...
    By writing an Adapter, a JDOMTreeModel class that implements TreeModel by using the JDOM API. Then, you could instantiate a JTree from that JDomTreeModel...

  • Xml in JTree: how to not collpase JTree node, when renaming XML Node.

    Hi.
    I'm writing some kind of XML editor. I want to view my XML document in JTree and make user able to edit contents of XML. I made my own TreeModel for JTree, which straight accesses XML DOM, produced by Xerces. Using DOM Events, I made good-looking JTree updates without collapsing JTree on inserting or removing XML nodes.
    But there is a problem. I need to produce to user some method of renaming nodes. As I know, there is no way to rename node in w3c DOM. So I create new one with new name and copy all children and attributes to it. But in this way I got a new object of XML Node instead of renamed one. And I need to initiate rebuilding (treeStructureChanged event) of JTree structure. Renamed node collapses. If I use treeNodesChanged event (no rebuilding, just changes string view of JTree node), then when I try to operate with renamed node again, exception will be throwed.
    Is there some way to rename nodes in my program without collpasing JTree?
    I'am new to Java. Maybe there is a method in Xerces DOM implementation to rename nodes without recreating?
    Thanks in advance.

    I assume that "rename" means to change the element name? Anyway your question seems to be "When I add a node to a JTree, how do I make sure it is expanded?" This is completely concerned with Swing, so it might have been better to post it in the Swing forum, but if it were me I would do this:
    1. Copy the XML document into a JTree.
    2. Allow the user to edit the document. Don't attempt to keep an XML document or DOM synchronized with the contents of the JTree.
    3. On request of the user, copy the JTree back to a new XML document.
    This way you can "rename" things to the user's heart's content without having the problem you described.

  • XML - JTree  in JBuilder environment

    Basically, my task is to create an basic java-xml based forum for part of my school project. My code has to be able to compile and run in JBuilder 7 Enterprise (Windows) without installing any extra APIs or XML Parsers [ :( ]. How do I do basic xml manipulations with JTree (i.e. read write) in this limited environment? Also I would love to see some sample codes on how to load xml into JTree. I haven't seen one around. Please advice. Thanks in advanced.

    try this:
    http://java.sun.com/j2ee/1.4/docs/tutorial/examples/jaxp/dom/samples/DomEcho02.java

  • JTree to XML??

    Hi,
    I am (still) trying to create XML from a JTree structure. I'm completely lost. Any help would be deadly!

    I didn't see anything in the API that suggests
    there's a standard way of doing this.And it would not make sense since a tree model just
    references objects without any indication as to how
    these could be either named in xml or written in xml.Yeah but I thought there might be an "XmlTreeModel" implementation of TreeModel. But apparently there isn't.
    Somebody must have made one though.
    On the other hand, whenever I've needed to show an XML file in a JTree, I just wrote a TreeNode wrapper. That worked fine, but didn't support adding elements. One could create a MutableTreeNode wrapper around XML.
    Actually it's probably so simple that maybe nobody has ever bothered to make something reusable. IIRC, a read-only TreeNode-around-DOM is about 40 lines of code. Mutable might be...100?

  • Processing large xml file (500mb)? break into small part? load into jtree

    hi,
    i'm doing an assignment to processing large xml file (500mb) and
    load into jree using JAVA.
    can someone advice me on the algorithm to do this?
    how can i load a 500mb xml in a jtree without system hang?
    how to i break my file and do the loading?

    1 Is the file schema based binary XML.
    2. The limits are dependant on storage model and chacater set.
    3. For all NON-XML content the current limit is 4GBytes (Where that is bytes not characters). So for Character content in an AL32UTF8 database the limit is 2GB
    4. For XML Content stored as CLOB the limit is the same as for character data (2GB/4GB) dependant on database character set.
    5. For SB Based XML content stored in Object Relatioanl storage the limit is determined by the complexity and structures defiend in the XML Schema

  • How to add xml cooments

    I have one xml file i created a swing application to modify that xml file.
    Know i want to add comments to that xml by using swing application.
    I don't want to change xml directly.
    And one more thing is iam representing the tags in xml as a jtree i want to set tool tip text for those tree
    nodes .

    that line should be added automatically to the document when you serilize your DOM.

  • Generate XML from tree

    I am trying to generate XML from a JTree. Does anyone know how I would go about it? I have been looking on google for examples but I can't find anything that would help.

    Have a method that takes a Node as its parameter. (I'm supposing you want each tree node to map to an element, but you didn't give any details.) Generate the opening tag for the element. Then for each child of the Node, pass the child to this same method recursively. Finally, generate the closing tag for the element.
    To get things started, call that method and pass it the root node of the tree.

  • Refreshing JTree with a customized TreeModel

    Hello,
    I'm newer to Swing, and I'm seeking for help for a JTree problem.
    I hoped to display an XML document with JTree. So I customized a TreeModel and TreeNode to handle the XML data.
    I used DOM to handle XML, and define TreeNode with the following class:
    class DOMtoTreeNode {
    org.w3c.dom.Node domNode;
    public DOMtoTreeNode(org.w3c.dom.Node myNode){
    this.domNode = myNOde; }
    public String toString() {
    //the displaying code
    //and other necessary code to handle children of domNode
    Then I defined an implementation of the TreeModel Interface.
    public class DomTreeModel implements javax.swing.tree.TreeModel
    Document document;
    public DomTreeModel(Document aDomDoc){   
         this.document = aDomDoc;
    // Basic TreeModel operations
    I didn't define any personal TreeModelListener for this TreeModel
    and then I created a JTree object to display the XML tree
    treeModel = new DomTreeModel(someDOMDocument);
    treeInputParameter = new JTree( treeModel );
    and I defined JtreeListener.
    What I hoped to do is to make modification for the XML document in the JTree.
    I added the editing functions in the "valueChanged" function. I added a new DOM node as a child of an existing element node by directly append the child in the DOM node. The code is like the follows:
    DOMToTreeNode treeNodeSelected =(DOMToTreeNode)
    treeInputParameter.getLastSelectedPathComponent();
    org.w3c.dom.Node domNode = treeNodeSelected.getNode();
    //get the dom node from Jtree Node here
    domNode.appendChild(someChildDomNode);
    Up to now, it seems work fine. The TreeModel updates the DOM Document, and the modification being shown in JTree.
    But when I tried to replace an existing node with a new node, something went wrong.
    domNode.replace(newChild, oldChild);
    I debugged the code, and found the underlying DOM Document in the TreeModel had been successfully changed, but the TreeModel didn't update the display in JTree.
    I'm afraid this is quite a naive question, but would someone be kindly help me deal with this? It seems that the reason is that some code is missing to let the TreeModel refresh the frontend JTree display. But I realy don't know how to tackle this.
    Thanks!
    Haoxiang Xia

    Thank you for your reply.
    Are you adding nodes or just expanding the JTree?Adding nodes (I also want to delete nodes)
    I don't know how to do this by just implementing
    TreeModel. This is using DefaultTreeModel.Yeah, I really don't want to use DefaultTreeModel because I would have to wrap my data objects as TreeNodes. Since my data objects are already in a tree structure, implementing TreeModel is much cleaner.
    It looks like I have to implement fireTreeNodesInserted() in my TreeModel, but I guess what I need to understand is how to register the JTree as a listener to my custom TreeModel. JTree doesn't directly implement TreeModelListener. I read somewhere that JTree automatically registers itself with the TreeModel, but that is not what I am observing.
    So..., I am still in need of more info.

  • Passing arraylist between constructors?

    Hi guys,
    I've pretty new to java, and I think i'm having a little trouble
    understanding scope. The program I'm working on is building a jtree
    from an xml file, to do this an arraylist (xmlText) is being built and
    declared in the function Main. It's then called to an overloaded
    constructor which processes the XML into a jtree:
    public Editor( String title, ArrayList xmlText ) throws
    ParserConfigurationException
    Later, in the second constructor which builds my GUI, I try and call
    the same arraylist so I can parse this XML into a set of combo boxes,
    but get an error thrown up at me that i'm having a hard time solving- :
    public Editor( String title ) throws ParserConfigurationException
    // additional code
    // Create a read-only combobox- where I get an error.
    String [] items = (String []) xmlText.toArray (new String[
    xmlText.size () ]);
    JComboBox queryBox = new JComboBox(items);
    JComboBox queryBox2 = new JComboBox(items);
    JComboBox queryBox3 = new JComboBox(items);
    JComboBox queryBox4 = new JComboBox(items);
    JComboBox queryBox5 = new JComboBox(items);
    This is the way I understand the Arraylist can be converted to a string
    to use in the combo boxs. However I get an error thrown up at me here
    at about line 206, which as far as I understand, is because when the
    overloaded constructor calls the other constructor:
    public Editor( String title ) throws ParserConfigurationException -
    It does not pass in the variable xmlText.
    I'm told that the compiler complains because xmlText is not defined
    at that point:
    - it is not a global variable or class member
    - it has not been passed into the function
    and
    - it has not been declared inside the current function
    Can anyone think of a solution to this problem? As I say a lot of this
    stuff is still fairly beyond me, I understand the principles behind the
    language and the problem, but the solution has been evading me so far.
    If anyone could give me any help or a solution here I'd be very
    grateful- I'm getting totally stressed over this.
    The code I'm working on is below, I've highlighted where the error
    crops up too- it's about line 200-206 area. Sorry for the length, I was
    unsure as to how much of the code I should post.
    public class Editor extends JFrame implements ActionListener
    // This is the XMLTree object which displays the XML in a JTree
    private XMLTree XMLTree;
    private JTextArea textArea, textArea2, textArea3;
    // One JScrollPane is the container for the JTree, the other is for
    the textArea
    private JScrollPane jScroll, jScrollRt, jScrollUp,
    jScrollBelow;
    private JSplitPane splitPane, splitPane2;
    private JPanel panel;
    // This JButton handles the tree Refresh feature
    private JButton refreshButton;
    // This Listener allows the frame's close button to work properly
    private WindowListener winClosing;
    private JSplitPane splitpane3;
    // Menu Objects
    private JMenuBar menuBar;
    private JMenu fileMenu;
    private JMenuItem newItem, openItem, saveItem,
    exitItem;
    // This JDialog object will be used to allow the user to cancel an exit
    command
    private JDialog verifyDialog;
    // These JLabel objects will be used to display the error messages
    private JLabel question;
    // These JButtons are used with the verifyDialog object
    private JButton okButton, cancelButton;
    private JComboBox testBox;
    // These two constants set the width and height of the frame
    private static final int FRAME_WIDTH = 600;
    private static final int FRAME_HEIGHT = 450;
    * This constructor passes the graphical construction off to the
    overloaded constructor
    * and then handles the processing of the XML text
    public Editor( String title, ArrayList xmlText ) throws
    ParserConfigurationException
    this( title );
    textArea.setText( ( String )xmlText.get( 0 ) + "\n" );
    for ( int i = 1; i < xmlText.size(); i++ )
    textArea.append( ( String )xmlText.get( i ) + "\n" );
    try
    XMLTree.refresh( textArea.getText() );
    catch( Exception ex )
    String message = ex.getMessage();
    System.out.println( message );
    }//end try/catch
    } //end Editor( String title, String xml )
    * This constructor builds a frame containing a JSplitPane, which in
    turn contains two
    JScrollPanes.
    * One of the panes contains an XMLTree object and the other contains
    a JTextArea object.
    public Editor( String title ) throws ParserConfigurationException
    // This builds the JFrame portion of the object
    super( title );
    Toolkit toolkit;
    Dimension dim, minimumSize;
    int screenHeight, screenWidth;
    // Initialize basic layout properties
    setBackground( Color.lightGray );
    getContentPane().setLayout( new BorderLayout() );
    // Set the frame's display to be WIDTH x HEIGHT in the middle of
    the screen
    toolkit = Toolkit.getDefaultToolkit();
    dim = toolkit.getScreenSize();
    screenHeight = dim.height;
    screenWidth = dim.width;
    setBounds( (screenWidth-FRAME_WIDTH)/2,
    (screenHeight-FRAME_HEIGHT)/2, FRAME_WIDTH,
    FRAME_HEIGHT );
    // Build the Menu
    // Build the verify dialog
    // Set the Default Close Operation
    // Create the refresh button object
    // Add the button to the frame
    // Create two JScrollPane objects
    jScroll = new JScrollPane();
    jScrollRt = new JScrollPane();
    // First, create the JTextArea:
    // Create the JTextArea and add it to the right hand JScroll
    textArea = new JTextArea( 200,150 );
    jScrollRt.getViewport().add( textArea );
    // Next, create the XMLTree
    XMLTree = new XMLTree();
    XMLTree.getSelectionModel().setSelectionMode(
    TreeSelectionModel.SINGLE_TREE_SELECTION
    XMLTree.setShowsRootHandles( true );
    // A more advanced version of this tool would allow the JTree to
    be editable
    XMLTree.setEditable( false );
    // Wrap the JTree in a JScroll so that we can scroll it in the
    JSplitPane.
    jScroll.getViewport().add( XMLTree );
    // Create the JSplitPane and add the two JScroll objects
    splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, jScroll,
    jScrollRt );
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(200);
    jScrollUp = new JScrollPane();
    jScrollBelow=new JScrollPane();
    // Here is were the error is coming up
    String [] items = (String []) xmlText.toArray (new String[
    xmlText.size () ]);
    JComboBox queryBox = new JComboBox(items);
    JComboBox queryBox2 = new JComboBox(items);
    JComboBox queryBox3 = new JComboBox(items);
    JComboBox queryBox4 = new JComboBox(items);
    JComboBox queryBox5 = new JComboBox(items);
    * I'm adding the scroll pane to the split pane,
    * a panel to the top of the split pane, and some uneditible
    combo boxes
    * to them. Then I'll rearrange them to rearrange them, but
    unfortunately am getting an error thrown up above.
    panel = new JPanel();
    panel.add(queryBox);
    panel.add(queryBox2);
    panel.add(queryBox3);
    panel.add(queryBox4);
    panel.add(queryBox5);
    jScrollUp.getViewport().add( panel );
    // Now building a text area
    textArea3 = new JTextArea(200, 150);
    jScrollBelow.getViewport().add( textArea3 );
    splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
    jScrollUp, jScrollBelow);
    splitPane2.setPreferredSize( new Dimension(300, 200) );
    splitPane2.setDividerLocation(100);
    splitPane2.setOneTouchExpandable(true);
    // in here can change the contents of the split pane
    getContentPane().add(splitPane2,BorderLayout.SOUTH);
    // Provide minimum sizes for the two components in the split pane
    minimumSize = new Dimension(200, 150);
    jScroll.setMinimumSize( minimumSize );
    jScrollRt.setMinimumSize( minimumSize );
    // Provide a preferred size for the split pane
    splitPane.setPreferredSize( new Dimension(400, 300) );
    // Add the split pane to the frame
    getContentPane().add( splitPane, BorderLayout.CENTER );
    //Put the final touches to the JFrame object
    validate();
    setVisible(true);
    // Add a WindowListener so that we can close the window
    winClosing = new WindowAdapter()
    public void windowClosing(WindowEvent e)
    verifyDialog.show();
    addWindowListener(winClosing);
    } //end Editor()
    * When a user event occurs, this method is called. If the action
    performed was a click
    * of the "Refresh" button, then the XMLTree object is updated using
    the current XML text
    * contained in the JTextArea
    public void actionPerformed( ActionEvent ae )
    if ( ae.getActionCommand().equals( "Refresh" ) )
    try
    XMLTree.refresh( textArea.getText() );
    catch( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    else if ( ae.getActionCommand().equals( "OK" ) )
    exit();
    else if ( ae.getActionCommand().equals( "Cancel" ) )
    verifyDialog.hide();
    }//end if/else if
    } //end actionPerformed()
    // Program execution begins here. An XML file (*.xml) must be passed
    into the method
    public static void main( String[] args )
    String fileName = "";
    BufferedReader reader;
    String line;
    ArrayList xmlText = null;
    Editor Editor;
    // Build a Document object based on the specified XML file
    try
    if( args.length > 0 )
    fileName = args[0];
    if ( fileName.substring( fileName.indexOf( '.' ) ).equals(
    ".xml" ) )
    reader = new BufferedReader( new FileReader( fileName )
    xmlText = new ArrayList();
    while ( ( line = reader.readLine() ) != null )
    xmlText.add( line );
    } //end while ( ( line = reader.readLine() ) != null )
    // The file will have to be re-read when the Document
    object is parsed
    reader.close();
    // Construct the GUI components and pass a reference to
    the XML root node
    Editor = new Editor( "Editor 1.0", xmlText );
    else
    help();
    } //end if ( fileName.substring( fileName.indexOf( '.' )
    ).equals( ".xml" ) )
    else
    Editor = new Editor( "Editor 1.0" );
    } //end if( args.length > 0 )
    catch( FileNotFoundException fnfEx )
    System.out.println( fileName + " was not found." );
    exit();
    catch( Exception ex )
    ex.printStackTrace();
    exit();
    }// end try/catch
    }// end main()
    // A common source of operating instructions
    private static void help()
    System.out.println( "\nUsage: java Editor filename.xml" );
    System.exit(0);
    } //end help()
    // A common point of exit
    public static void exit()
    System.out.println( "\nThank you for using Editor 1.0" );
    System.exit(0);
    } //end exit()
    class newMenuHandler implements ActionListener
    public void actionPerformed( ActionEvent ae )
    textArea.setText( "" );
    try
    // Next, create a new XMLTree
    XMLTree = new XMLTree();
    XMLTree.getSelectionModel().setSelectionMode(
    TreeSelectionModel.SINGLE_TREE_SELECTION );
    XMLTree.setShowsRootHandles( true );
    // A more advanced version of this tool would allow the JTree
    to be editable
    XMLTree.setEditable( false );
    catch( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    }//end actionPerformed()
    }//end class newMenuHandler
    class openMenuHandler implements ActionListener
    JFileChooser jfc;
    Container parent;
    int choice;
    openMenuHandler()
    super();
    jfc = new JFileChooser();
    jfc.setSize( 400,300 );
    jfc.setFileFilter( new XmlFileFilter() );
    parent = openItem.getParent();
    }//end openMenuHandler()
    public void actionPerformed( ActionEvent ae )
    // Displays the jfc and sets the dialog to 'open'
    choice = jfc.showOpenDialog( parent );
    if ( choice == JFileChooser.APPROVE_OPTION )
    String fileName, line;
    BufferedReader reader;
    fileName = jfc.getSelectedFile().getAbsolutePath();
    try
    reader = new BufferedReader( new FileReader( fileName ) );
    textArea.setText( reader.readLine() + "\n" );
    while ( ( line = reader.readLine() ) != null )
    textArea.append( line + "\n" );
    } //end while ( ( line = reader.readLine() ) != null )
    // The file will have to be re-read when the Document
    object is parsed
    reader.close();
    XMLTree.refresh( textArea.getText() );
    catch ( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    jfc.setCurrentDirectory( new File( fileName ) );
    } //end if ( choice == JFileChooser.APPROVE_OPTION )
    }//end actionPerformed()
    }//end class openMenuHandler
    class saveMenuHandler implements ActionListener
    JFileChooser jfc;
    Container parent;
    int choice;
    saveMenuHandler()
    super();
    jfc = new JFileChooser();
    jfc.setSize( 400,300 );
    jfc.setFileFilter( new XmlFileFilter() );
    parent = saveItem.getParent();
    }//end saveMenuHandler()
    public void actionPerformed( ActionEvent ae )
    // Displays the jfc and sets the dialog to 'save'
    choice = jfc.showSaveDialog( parent );
    if ( choice == JFileChooser.APPROVE_OPTION )
    String fileName;
    File fObj;
    FileWriter writer;
    fileName = jfc.getSelectedFile().getAbsolutePath();
    try
    writer = new FileWriter( fileName );
    textArea.write( writer );
    // The file will have to be re-read when the Document
    object is parsed
    writer.close();
    catch ( IOException ioe )
    ioe.printStackTrace();
    }//end try/catch
    jfc.setCurrentDirectory( new File( fileName ) );
    } //end if ( choice == JFileChooser.APPROVE_OPTION )
    }//end actionPerformed()
    }//end class saveMenuHandler
    class exitMenuHandler implements ActionListener
    public void actionPerformed( ActionEvent ae )
    verifyDialog.show();
    }//end actionPerformed()
    }//end class exitMenuHandler
    class XmlFileFilter extends javax.swing.filechooser.FileFilter
    public boolean accept( File fobj )
    if ( fobj.isDirectory() )
    return true;
    else
    return fobj.getName().endsWith( ".xml" );
    }//end accept()
    public String getDescription()
    return "*.xml";
    }//end getDescription()
    }//end class XmlFileFilter
    } //end class Editor
    Sorry if this post has been a bit lengthy, any help you guys could give
    me solving this would be really appreciated.
    Thanks,
    Iain.

    Hey. Couple pointers:
    When posting, try to keep code inbetween code tags (button between spell check and quote original). It will pretty-print the code.
    Posting code is good. Usually, though, you want to post theminimum amount of code which runs and shows your problem.
    That way people don't have to wade through irrelevant stuff and
    they have an easier time helping.
    http://homepage1.nifty.com/algafield/sscce.html
    As for your problem, this is a scope issue. You declare an
    ArrayList xmlText in main(). That means that everywhere after
    the declaration in main(), you can reference your xmlText.
    So far so good. Then, inside main(), you call
    Editor = new Editor( "Editor 1.0", xmlText );Now you've passed the xmlText variable to a new method,
    Editor(String title, ArrayList xmlText) [which happens to be a
    constructor, but that's not important]. When you do that, you
    make the two variables title and xmlText available to the whole
    Editor(String, ArrayList) method.
    This is where you get messed up. You invoke another method
    from inside Editor(String, ArrayList). When you call
    this(title);you're invoking the method Editor(String title). You aren't passing
    in your arraylist, though. You've got code in the Editor(String) method
    which is trying to reference xmlText, but you'd need to pass in
    your ArrayList in order to do so.
    My suggestion would be to merge the two constructor methods into
    one, Editor(String title, ArrayList xmlText).

  • How to make some nodes invisible?

    I set up a xml tree with JTree.Now I want to make some nodes invisible like the nodes which the name of the node is "datatype",how can I ?Thank you.

    I don't know if the nodes can be made invisible. But if you make cell renderer then you can evaluate the value before displaying it. If value is like 'datatype', you display (cell renderer displays) nothing as value in the cell.

  • Help please with a Static Initializer for ImageIcons inside Jar Files

    At the moment I'm playing around displaying XML using A JTree
    I am subclassing DefaultMutableTreeNode, and want it to have some default Icons set up....
    Sort of like this:
    public class XNode extends DefaultMutableTreeNode
        public static final ImageIcon icon;
       public static ImageIcon getIcon()
            return XNode.icon;
    }The only thing is that for the life of me after trying various things and searching these forums and google:
    I can't work out how to write the static Initializer for the ImageIcon.
    The ImageIcon will need to be created using a URL, cos it will be inside my jar file.....
    the usual...
               URL url = this.getClass().getResource("/images/Exit16.gif");
               ImageIcon Icon = new ImageIcon( url );but I wanted these Icons to be class members..............
    Could someone help?
    }

    DrClap " I don't understand why you put Class.forName in there either"
    A: Because I don't really know what I'm doing.
    I will try that suggestion.
    At present I have this:
         static ImageIcon loadIcon;
         static
              try
                loadIcon = new ImageIcon( Class.forName("cis.editor.xml.nodes.AlNode").getResource("/images/Exit16.gif"));
              catch( ClassNotFoundException cnfe )
                   System.out.println("ClassNotFound: " + cnfe.getMessage() );
         public static final ImageIcon defaultIcon = loadIcon;
         static
              try
                loadIcon = new ImageIcon( Class.forName("cis.editor.xml.nodes.AlNode").getResource("/images/tree_folder_major.gif"));
              catch( ClassNotFoundException cnfe )
                   System.out.println("ClassNotFound: " + cnfe.getMessage() );
         public static final ImageIcon commentIcon = loadIcon;
    //.......... ANd so OnWhy? Because do far it was the only way I could get it to compile.
    And It works..
    However it's a real abortion.. codewise.
    I need to load about 16 Icons that the various subclasses can 'use'
    DefaultTreeCellRenderer - must do somethng similar because it has a bunch of Icons to "Pick from",
    Only How is that done 'properly' ?

  • Problem with Jtree to xml tranform..how to set/get parent of a node?

    Hi,
    I am trying to develop xml import/export module.In import wizard, I am parsing the xml file and the display it in Jtree view using xml tree model which implements TreeModel and xml tree node.I am using jaxp api..
    It is workin fine.
    I got stuck with removal of selected node and save it as a new xml.
    I am not able to get parent node of selected node in remove process,itz throwing null.I think i missed to define parent when i load treemodel.Plz help me out..give some ideas to do it..
    thanks
    -bala
    Edited by: r_bala on May 9, 2008 4:44 AM

    there's no way anyone can help you without seeing your code.

Maybe you are looking for

  • Using a rule in a BPM process

    Good day. I created an emdeded rule in the process composer and want to use it in the context processing (change value of the input variable). The rule is very simple - it receives a value and should return the other: In: ValSome, out: 1 In: ValOther

  • When i boot my mac it opens with a grey screen and the wireless keyboard, mouse illustration and won't do anything elsens,

    When I turn on my iMac (27" intel) all I get is connect my wireless keyboard and mouse on a grey screen. The mouse will connect (sometimes) after I wiggle it a bit, but nothing from the keyboard. After a few minutes the disk utilities box comes up. I

  • How to use java to create an XML document from an SQL database?

    Hi, I'm a complete novice at XML and have only recently started programming in Java. I'm currently trying to develop a package in Java 1.1.8 which requires a set of very specifically formatted XML documents. These documents would need to be updated r

  • Error while opening administrator Editior

    Experts! When I open HANA studio I see the error's  below could any one help. when I place cursor on systems  -  Local host - system state can't be determined  , SAP control request failed : Unexpected end of file from server I see this error when I

  • Network Design related

    Hi there. I have a question regarding when would be the appropriate design scenario to move from fixed stackable switches to modular chassis swithes. Is it technology depended or a specific cut off point (users) that you would move away from fixed co