Checkboxes as nodes in JTree

Hi,
I'm wondering if there's a relatively easy way of getting JCheckboxes instead of JLabels to appear as the nodes in a JTree. Any advice on the best way to do this would be much appreciated,
colin

http://www.mutualinstrument.com/Easy/tree_01.gif
http://www.mutualinstrument.com/Easy/FAQ/Tree/tree.html

Similar Messages

  • Help needed with finding node in JTree

    Hi,
    In my application i will be entering some string data in a text box for search criteria.
    When I click on search, I will get data from database which will be shown as a JTree.
    This Jtree will have some nodes in which, node with string entered in the search text box exists.
    I need to focus on this node and I have only a string to find this node.
    How can I do this?How can I find a node in JTree using string value?
    Is there any alternate option by which I can achive my need?
    Please suggest.
    Thanks.

    @OP: please assign your dukes.
    @Andre_Uhres: if you don't get rewarded in the next couple of days, please let me know here to get at least one duke for your effort.
    Bye.

  • Problem inserting new node into JTree with depthFirstEnumeration()

    Hello,
    I'm currently trying to use depthFirstEnumeration() to add and delete nodes for a simple JTree. I've written a method to handle this, but it keeps coming back with an exception saying that 'new child is an ancestor'.
    All I'm trying to do is add and delete nodes from a JTree using add and remove buttons within a swing program. When a user adds the new node the JTree needs to be updated with new labels in sequential order dependent upon a depthFirst traversal of the JTree.
    My current code for the add button is as follows,
    public void actionPerformed(ActionEvent event) 
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            Enumeration e = rootNode.depthFirstEnumeration();
            if(event.getSource().equals(addButton))
                if (selectedNode != null)
                    while (e.hasMoreElements()) {
                    // add the new node as a child of a selected node at the end
                    DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)e.nextElement();
                     // treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                    //System.out.print(newNode.getUserObject() + "" + newNodeSuffix++);
                    String label = "Node"+i;
                    treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                    i++;
                      //make the node visible by scrolling to it
                    TreeNode[] totalNodes = treeModel.getPathToRoot(newNode);
                    TreePath path = new TreePath(totalNodes);
                    tree.scrollPathToVisible(path);
                    //System.out.println();
            else if(event.getSource().equals(deleteButton))
                //remove the selected node, except the parent node
                removeSelectedNode();           
        } As you can see in the above code, I've tested the incrementing of the new nodes in a System.out.print() statement and they appear to be incrementing correctly. I just can't see how to correctly output the labels for the nodes.
    Any help and advice always appreciated.

    This is about the 5th posting on the same question. Here is the link to the last posting so you can see what has already been suggested so you don't waste your time making the same suggestion.
    http://forum.java.sun.com/thread.jspa?threadID=704980
    The OP doesn't seem to understand that nodes don't just rename themselves and that renderers will only display the text of the current node. If you want the text displayed to changed, then you need to change the text associated with each node, which means iterating through the entire tree to update each node with new text. Then again, maybe I don't understand the question, but the OP keeps posting the same question without any additional information.

  • Drag and Drop nodes in JTree

    Is there a way to drap and drop JTree nodes without resorting to hacks? http://www.javaworld.com/javatips/jw-javatip97.html outlines a hack to get drag and drop working but it is kinda old. I am wondering whether there is a now a way to do this in Swing. http://weblogs.java.net/blog/shan_man/archive/2006/01/first_class_dra.html outlines a seemingly promising way but when I tried it it still wouldn't let me drag JTree nodes. (btw, if you are going to try it, you must replace TransferHandler.TransferInfo with TransferHandler.TransferSupport. It has apprently been renamed.)

    I have implemented drag and drop of nodes in JTree they same way it is explained in JavaWorld link that you mentioned, I customized it for my application and it worked great.

  • Wordwrap nodes in jtree

    Anyone know how we can do wordwrap of nodes in jtree?
    Please help...
    Thanks.

    Any example on this? what html code should I use? The simplest possible, eg
    yourNode.setText("<html>" + yourNodeText + "</html>");Most JComponents can render this html string and produce a good result. But if you wanna get a little more complex and use styles and other web things, then do as said, (two posts above) and use a JEditorPane specifically for cell renderer
    ICE

  • How to set the default tree node in JTree?

    I want to set a default tree node in JTree when start the program,
    what is the method or the function to call?
    Thanks~

    If you by "default" mean "selected", then you can use one of the setSelectionXXX methods in the JTree API.
    If you by "default" mean something else, never mind this post :-)

  • Setting custom color for selected node in JTree?

    Hi,
    i want to set my own color for selected node in JTree. i don't want to set for all the nodes...how to set Color for Selected node using TreeCellRender class?
    Thanks
    Mani

    I assume you are not setting a custom tree cell renderer...
    javax.swing.JTree theTree = ...;
    java.awt.Color newBGColor = ...;
    ((javax.swing.tree.DefaultTreeCellRenderer)theTree.getCellRenderer())
        .setBackgroundSelectionColor(newColor);

  • Add node to JTree

    I have an already populated JTree. At Runtime I add one or more node to JTree, using something like
    parentNode.add(newNode)....
    If I call a repaint method, the new node isn't visible, I have to reload model using
    DefaultTreeModel dtm = ((DefaultTreeModel)myTree.getModel());
    TreeNode rootNode = (TreeNode) dtm.getRoot();
    dtm.reload(rootNode);
    Unfortunately this method cause the lost of focus on the currently selected node and the collapse of all JTree around its root node; If I change an existing node (for example changing its text or icon) I must reload the model too!!!
    Does exist an other more "soft" method to change the aspect of a JTree without reload the entire model?

    You must use or implement the
        public void valueForPathChanged(javax.swing.tree.TreePath path,java.lang.Object newNode) {
            Object[]    p = path.getPath();
            Object[]    pp = p;
            //insert node here
            int[] ci = new int[] {index};
            Object[] cc = new Object[] {node};
            fireTreeNodesChanged(this, pp, ci, cc);
            fireTreeStructureChanged(this, pp, ci, cc);
        }from the TreeModel. To fire the last two is essensial.
    I implemented a GP in JAVA so i had the same problem wehn i started.

  • How to dynamically add Nodes to JTree?

    How to add nodes to a Jtree by getting the information into a specific file
    For example, in JList:
    DefaultListModel workgroups;
    workgroups = new DefaultListModel();
    List<String> workgroupsList = new ArrayList<String>();
    workgroupsList = ParserUtils.getWorkgroupList(ParserUtils.getConfigPath() + "\\.workgroup.properties");
    if (!workgroupsList.isEmpty()){
         for (String workgroup : workgroupsList){
              workgroups.addElement(workgroup.toString().trim());
    workgroupList = new JList(workgroups); //adds the list workgroupsThe output of this will be a JList displaying the list of workgroups per line. The list could be found in a file name "workgroup.properties"
    Question is, is it possible to adapt this same method in JTree. The information per line will serve as one node in the tree. For example, I have 3 workgroups in the list, there will also be 3 nodes to be found in the tree.
    Any suggestions?
    THanks.

    There's a huge JTree example in the Swing tutorial. It's a bit of a beast to use.

  • How to show only all children of selected node in JTree??

    Dear friends:
    I have Two Panels, PA and PB,
    PA has a Jtree as code below, and PB listens to PA,
    I hope to do following,
    If I select a node called A in PA, then Node A's all children such as A1, A2, A3 will be displayed in PB, but not display A1, A2, A3's children such as A3 has C1, C2, C3, C4 & C5, until I select A3 then PB will display only all A3's children: C1, C2, C3, C4 & C5;
    i.e, only populate each ONE level of children of Node A or any node I select, not its grandchildren and its grand-grand children;
    Please help how to do it??
    I tried amny times, failed.
    Thanks
    [1]. PA panel code:
    package com.atest;
         import java.awt.BorderLayout;
         import java.awt.event.MouseAdapter;
         import java.awt.event.MouseEvent;
         import java.util.Enumeration;
         import java.awt.Dimension;
         import javax.swing.JFrame;
         import javax.swing.JPanel;
         import javax.swing.JScrollPane;
         import javax.swing.JTextField;
         import javax.swing.JTree;
         import javax.swing.tree.DefaultMutableTreeNode;
         import javax.swing.tree.TreeModel;
         import javax.swing.tree.TreePath;
         public class DefaultMutableTreeMain extends JPanel {
         protected DefaultMutableTreeNode    top = new DefaultMutableTreeNode("Options");
         protected DefaultMutableTreeNode      selectedNode = null;
         protected final JTree tree;
         protected final JTextField jtf;
        protected Enumeration      vEnum = null;
         private      TreeModel                m;
         protected  DefaultMutableTreeNode      getDefaultMutableTreeNode()  {
              //textArea.getText();
                   return selectedNode;
         protected  DefaultMutableTreeNode setDefaultMutableTreeNode(DefaultMutableTreeNode tt)  {
              //textArea.getText();
                   selectedNode = tt;
                   return selectedNode;
         protected  TreeModel getJTModel()  {
              //textArea.getText();
                   return m;
         protected  TreeModel setJTModel(TreeModel ta)  {
                   m = ta;
                   return m;
           public DefaultMutableTreeMain() {
             setSize(300,300);
             setLayout(new BorderLayout());
             DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
             top.add(a);
             DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
             a.add(a1);
             DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
             a.add(a2);
             DefaultMutableTreeNode a3 = new DefaultMutableTreeNode("A3");
             a.add(a3);
             DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
             top.add(b);
             DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
             b.add(b1);
             DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
             b.add(b2);
             DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
             b.add(b3);
             DefaultMutableTreeNode c = new DefaultMutableTreeNode("C");
             a3.add(c);
             DefaultMutableTreeNode c1 = new DefaultMutableTreeNode("C1");
             c.add(c1);
             DefaultMutableTreeNode c2 = new DefaultMutableTreeNode("C2");
             c.add(c2);
             DefaultMutableTreeNode c3 = new DefaultMutableTreeNode("C3");
             c.add(c3);
             DefaultMutableTreeNode c4 = new DefaultMutableTreeNode("C4");
             c.add(c4);
             DefaultMutableTreeNode c5 = new DefaultMutableTreeNode("C5");
             c.add(c5);
             tree = new JTree(top);
             JScrollPane jsp = new JScrollPane(tree);
             jsp.setPreferredSize(new Dimension(400,300));
             add(jsp, BorderLayout.CENTER);
             jtf = new JTextField("", 20);
             add(jtf, BorderLayout.SOUTH);
               tree.addMouseListener(new MouseAdapter() {
               public void mouseClicked(MouseEvent me) {
                  TreePath   path = tree.getSelectionPath();
                  DefaultMutableTreeNode      selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                 TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
                 setDefaultMutableTreeNode(selectedNode);
                     System.out.println("Current node selected is (tp.toString()=" + tp.toString());
                     System.out.println("Current node selected is getDefaultMutableTreeNode()=" + getDefaultMutableTreeNode());
                 if (tp != null){
                     jtf.setText(tp.toString());
                      System.out.println("It Has Children as selectedNode.getChildCount()= " + selectedNode.getChildCount());
                            Enumeration vEnum = selectedNode.children();
                                int i = 0;
                                while(vEnum.hasMoreElements()){
                                    System.out.println("2 selectedNode = " +  path.toString() + "  has " + i++ + " Children in vEnum.nextElement(" + i + ") = " + vEnum.nextElement());
                 else
                   jtf.setText("");
           public static void main(String[] args) {
             JFrame frame = new JFrame();
             frame.getContentPane().add(new DefaultMutableTreeMain());
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setSize(400, 400);
             frame.setVisible(true);
         }[2]. PB Panel code
    package com.atest;
    import java.awt.BorderLayout;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.JPanel;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.*;
    import javax.swing.JButton;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    public class DefaultMutableTreeSub extends JPanel implements java.io.Serializable{
      private JButton removeButton;
      private JButton addButton;
      JTree tree;
      private TreeModel      m;
      protected TreeDragSource ds;
      protected TreeDropTarget dt;
    protected  TreeModel getJTModel()  {
              //textArea.getText();
                   return m;
    protected  TreeModel setJTModel(TreeModel ta)  {
                   m = ta;
                   return m;
    protected DefaultTreeModel model;
    protected DefaultMutableTreeNode rootNode;
    DefaultMutableTreeMain dmm = null;
    JPanel inputPanel  = new JPanel();
      public JPanel SLTreeDNDEditableDynamic(DefaultMutableTreeMain tdnd ) {
        //super("Rearrangeable Tree");
        setSize(400,450);
        dmm = tdnd;
             setLayout(new BorderLayout());
             inputPanel.setLayout(new BorderLayout());
             JPanel outputPanel = new JPanel();
             System.out.println("Sub selectedNode tdnd= " + tdnd);
             tdnd.tree.addTreeSelectionListener(new TreeSelectionListener(){
                  public void valueChanged(TreeSelectionEvent evt){
                  TreePath[] paths = evt.getPaths();
                  TreePath   path = dmm.tree.getSelectionPath();
                  DefaultMutableTreeNode      selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                 DefaultMutableTreeNode itemNode = dmm.getDefaultMutableTreeNode();
                     System.out.println("Sub node selected is dmm.getDefaultMutableTreeNode()=" + dmm.getDefaultMutableTreeNode());
                  model = new DefaultTreeModel(itemNode);
                  tree = new JTree(model);
                  System.out.println("Sub selectedNode paths= " + paths);
                  System.out.println("Sub selectedNode path= " + path);
                  System.out.println("Sub selectedNode = " + selectedNode);
                  System.out.println("Sub itemNode = " + itemNode);
                  tree.putClientProperty("JTree.lineStyle", "Angled");
                  tree.setRootVisible(true);
                   inputPanel.add(new JScrollPane(tree),BorderLayout.CENTER);
             return inputPanel;
         public DefaultMutableTreeSub() {
              super();
    }thanks
    sunny

    Thanks so much, I use your code and import followig:
    import java.util.ArrayList;
    import java.awt.List;
    but
    private static List<Object> getChildNodes(JTree j) {
         Object parent = j.getLastSelectedPathComponent();
         int childNodeCount = j.getModel().getChildCount(parent);
         List<Object> results = new ArrayList()<Object>;
         for (i = 0; i < childNodeCount; i++) {
              results.add(parent, i);
         return results;
    here List<Object> and ArrayList()<Object> show red,
    Is my JDK version problem??
    my one is JKD
    C:\temp\swing>java -version
    java version "1.4.2_08"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_08-b03)
    Java HotSpot(TM) Client VM (build 1.4.2_08-b03, mixed mode)
    Error as follows:
    C:\temp\swing>javac DefaultMutableTreeSub.java
    DefaultMutableTreeSub.java:38: <identifier> expected
    private static List<Object> getChildNodes(JTree j) {
    ^
    1 error
    any idea??
    Thanks

  • How to search a child node in JTree

    Hi I am new to swings..
    My requirement is I have a Jsplit pane.
    I have search button with a text box in one and Jree in another pane.
    When I enter a string and hit Search button...It need to search the tree and expand that node highlight it.
    can anyone help in getting this done.

    public void actionPerformed(ActionEvent e)
      DefaultTreeModel m_model = new DefaultTreeModel(entityRoot);
      DefaultMutableTreeNode node = searchNode(m_searchText.getText());
      JTree m_tree = new JTree(m_model);
      TreePath root = m_tree.getPathForRow(0);
      searchTree(m_tree, root, m_searchText.getText());
    private void searchTree(JTree tree, TreePath path, String q)
    TreeNode node = (TreeNode)path.getLastPathComponent();
    if(node==null) return;
    if(node.toString().startsWith(q))
       tree.setScrollsOnExpand(true);
       tree.setSelectionPath(path);
    if(!node.isLeaf() && node.getChildCount()>=0)
       Enumeration e = node.children();
       while(e.hasMoreElements())
       searchTree(tree, path.pathByAddingChild(e.nextElement()), q);
    }Edited by: EJP on 27/06/2011 09:53: added {noformat}{noformat} tags. Please use them.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Change icon of a non selected node in JTree

    Hello
    I have a swing application contening a JTree.
    I'd like to know how to change the icon of a non selected node in my tree. I have the information about the node and its path. I try to change userObject information and the icon of the node with the setIcon of (DefaultMutableTreeNode), and reload the node (DefaultTreeModel) but it doesn't work.
    Do I have to set the change in my CellRenderer ?
    Any advice will be welcome
    Anne

    If you carefully look at the java tutorial tree, the change is made for all the leaf icon. What I want is to change the icon of a not selected node of my tree while I do other stuff with the other nodes like select, display their contents, drag them ...
    the operation of a not selected node is independant from the selection in the tree.
    So I still ask how to force a node to reload and take care of the change of his icon.
    Anne

  • How to cut, copy and paste a tree node in JTree?????

    Hi, Java GUI guru. Thank you for your help in advance.
    I am working on a File Explorer project with JTree. There are cut, copy and paste item menus in my menu bar. I need three EventAction methods or classes to implements the three tasks. I tried to use Clipboard to copy and paste tree node. But I can not copy any tree node from my tree.
    Are there any body has sample source code about cut, copy, and paste for tree? If possible, would you mind send me your sample source code to [email protected]
    I would appreciate you very very much for your help!!!!
    X.G.

    Hi, Paul Clapham:
    Thank you for your quick answer.
    I store the node in a DefaultMutableTreeNode variable, and assign it to another DefaultMutableTreeNode variable. I set up two classes (CopyNode and PasteNode). Here they are as follows:
    //CopyNode class
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class CopyNode implements ActionListener{
    private TreeList jtree;
    String treeNodeName;
    TreePath currentSelection;
    DefaultMutableTreeNode currentNode;
    public CopyNode(TreeList t){
    jtree = t;
    public void actionPerformed(ActionEvent e){
    currentSelection = jtree.tree.getSelectionPath();
    if(currentSelection != null){
    currentNode = (DefaultMutableTreeNode)(currentSelection.getLastPathComponent());
    treeNodeName = currentNode.toString();
    //PasteNode class
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class PasteNode extends DefaultMutableTreeNode{
    private TreeList jtree;
    CopyNode copyNode;
    public PasteNode(TreeList t){
    jtree = t;
    copyNode = new CopyNode(t);
    public DefaultMutableTreeNode addObject(Object child){
    DefaultMutableTreeNode parentNode = null;
    TreePath parentPath = jtree.tree.getSelectionPath();
    if(parentPath == null){
    parentNode = jtree.root;
    else{
    parentNode = (DefaultMutableTreeNode)parentPath.getLastPathComponent();
    return addObject(parentNode, child, true);
    public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible){
    DefaultMutableTreeNode childNode = copyNode.currentNode;
    if(parent == null){
    parent = jtree.root;
    jtree.treemodel.insertNodeInto(childNode, parent, parent.getChildCount());
    if(shouldBeVisible){
    jtree.tree.scrollPathToVisible(new TreePath(childNode.getPath()));
    return childNode;
    I used these two classes objects in "actionPerformed(ActionEvent e)" methods in my tree:
    //invoke copyNode
    copyItem = new JMenuItem("Copy");
    copyItem.addActionListener(copyNode);
    //invoke pasteNode
    pasteItem = new JMenuItem("Paste");
    pasteItem.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
    pasteName.addObject(copyName.treeNodeName);
    When I run the drive code, making a copy some node from my tree list, I got bunch of error messages.
    Can you figour out what is wrong in my two classes? If you have sample code, would you mind mail me for reference.
    Thank you very much in advance.
    X.G.

  • Remove white space nodes from jtree

    I am trying to create jtree using XML DOM.
    But I m not able to remove/ignore the white space elements from DOM.
    I am getting output something like this
    for example
    Server
    Text
    node1
    Text
    I want something like this.
    Server
    node1
    I tried all option for removeing the white space
    Here I am posting the source
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import java.io.File;
    import java.io.IOException;
    import org.w3c.dom.Document;
    import org.w3c.dom.DOMException;
    // Basic GUI components
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    // GUI components for right-hand side
    import javax.swing.JSplitPane;
    import javax.swing.JEditorPane;
    // GUI support classes
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    // For creating borders
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.CompoundBorder;
    // For creating a TreeModel
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.util.*;
    public class DomEcho02 extends JPanel
    // Global value so it can be ref'd by the tree-adapter
    static Document document;
    static final int windowHeight = 460;
    static final int leftWidth = 300;
    static final int rightWidth = 340;
    static final int windowWidth = leftWidth + rightWidth;
    public DomEcho02()
    // Make a nice border
    EmptyBorder eb = new EmptyBorder(5,5,5,5);
    BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
    CompoundBorder cb = new CompoundBorder(eb,bb);
    this.setBorder(new CompoundBorder(cb,eb));
    // Set up the tree
    JTree tree = new JTree(new DomToTreeModelAdapter());
    // Iterate over the tree and make nodes visible
    // (Otherwise, the tree shows up fully collapsed)
    //TreePath nodePath = ???;
    // tree.expandPath(nodePath);
    // Build left-side view
    JScrollPane treeView = new JScrollPane(tree);
    treeView.setPreferredSize(
    new Dimension( leftWidth, windowHeight ));
    // Build right-side view
    JEditorPane htmlPane = new JEditorPane("text/html","");
    htmlPane.setEditable(false);
    JScrollPane htmlView = new JScrollPane(htmlPane);
    htmlView.setPreferredSize(
    new Dimension( rightWidth, windowHeight ));
    // Build split-pane view
    JSplitPane splitPane =
    new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
    treeView,
    htmlView );
    splitPane.setContinuousLayout( true );
    splitPane.setDividerLocation( leftWidth );
    splitPane.setPreferredSize(
    new Dimension( windowWidth + 10, windowHeight+10 ));
    // Add GUI components
    this.setLayout(new BorderLayout());
    this.add("Center", splitPane );
    } // constructor
    public static void main(String argv[])
    if (argv.length != 1) {
    System.err.println("Usage: java DomEcho filename");
    System.exit(1);
    DocumentBuilderFactory factory =
    DocumentBuilderFactory.newInstance();
    //factory.setValidating(true);
    //factory.setNamespaceAware(true);
    try {
    DocumentBuilder builder = factory.newDocumentBuilder();
    document = builder.parse( new File(argv[0]) );
    makeFrame();
    } catch (SAXException sxe) {
    // Error generated during parsing)
    Exception x = sxe;
    if (sxe.getException() != null)
    x = sxe.getException();
    x.printStackTrace();
    } catch (ParserConfigurationException pce) {
    // Parser with specified options can't be built
    pce.printStackTrace();
    } catch (IOException ioe) {
    // I/O error
    ioe.printStackTrace();
    } // main
    public static void makeFrame() {
    // Set up a GUI framework
    JFrame frame = new JFrame("DOM Echo");
    frame.addWindowListener(
    new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    // Set up the tree, the views, and display it all
    final DomEcho02 echoPanel =
    new DomEcho02();
    frame.getContentPane().add("Center", echoPanel );
    frame.pack();
    Dimension screenSize =
    Toolkit.getDefaultToolkit().getScreenSize();
    int w = windowWidth + 10;
    int h = windowHeight + 10;
    frame.setLocation(screenSize.width/3 - w/2,
    screenSize.height/2 - h/2);
    frame.setSize(w, h);
    frame.setVisible(true);
    } // makeFrame
    // An array of names for DOM node-types
    // (Array indexes = nodeType() values.)
    static final String[] typeName = {
    "none",
    "Element",
    "Attr",
    "Text",
    "CDATA",
    "EntityRef",
    "Entity",
    "ProcInstr",
    "Comment",
    "Document",
    "DocType",
    "DocFragment",
    "Notation",
    // This class wraps a DOM node and returns the text we want to
    // display in the tree. It also returns children, index values,
    // and child counts.
    public class AdapterNode
    org.w3c.dom.Node domNode;
    // Construct an Adapter node from a DOM node
    public AdapterNode(org.w3c.dom.Node node) {
    domNode = node;
    // Return a string that identifies this node in the tree
    // *** Refer to table at top of org.w3c.dom.Node ***
    public String toString() {
    String s = typeName[domNode.getNodeType()];
    String nodeName = domNode.getNodeName();
    if (! nodeName.startsWith("#")) {
    s += ": " + nodeName;
    if (domNode.getNodeValue() != null) {
    if (s.startsWith("ProcInstr"))
    s += ", ";
    else
    s += ": ";
    // Trim the value to get rid of NL's at the front
    String t = domNode.getNodeValue().trim();
    int x = t.indexOf("\n");
    if (x >= 0) t = t.substring(0, x);
    s += t;
    return s;
    * Return children, index, and count values
    public int index(AdapterNode child) {
    //System.err.println("Looking for index of " + child);
    int count = childCount();
    for (int i=0; i<count; i++) {
    AdapterNode n = this.child(i);
    if (child.domNode == n.domNode) return i;
    return -1; // Should never get here.
    public AdapterNode child(int searchIndex) {
    //Note: JTree index is zero-based.
    org.w3c.dom.Node node =
    domNode.getChildNodes().item(searchIndex);
    return new AdapterNode(node);
    public int childCount() {
    return domNode.getChildNodes().getLength();
    // This adapter converts the current Document (a DOM) into
    // a JTree model.
    public class DomToTreeModelAdapter
    implements javax.swing.tree.TreeModel
    // Basic TreeModel operations
    public Object getRoot() {
    //System.err.println("Returning root: " +document);
    return new AdapterNode(document);
    public boolean isLeaf(Object aNode) {
    // Determines whether the icon shows up to the left.
    // Return true for any node with no children
    AdapterNode node = (AdapterNode) aNode;
    if (node.childCount() > 0) return false;
    return true;
    public int getChildCount(Object parent) {
    AdapterNode node = (AdapterNode) parent;
    return node.childCount();
    public Object getChild(Object parent, int index) {
    AdapterNode node = (AdapterNode) parent;
    return node.child(index);
    public int getIndexOfChild(Object parent, Object child) {
    AdapterNode node = (AdapterNode) parent;
    return node.index((AdapterNode) child);
    public void valueForPathChanged(TreePath path, Object newValue) {
    // Null. We won't be making changes in the GUI
    // If we did, we would ensure the new value was really new,
    // adjust the model, and then fire a TreeNodesChanged event.
    * Use these methods to add and remove event listeners.
    * (Needed to satisfy TreeModel interface, but not used.)
    private Vector listenerList = new Vector();
    public void addTreeModelListener(TreeModelListener listener) {
    if ( listener != null
    && ! listenerList.contains( listener ) ) {
    listenerList.addElement( listener );
    public void removeTreeModelListener(TreeModelListener listener) {
    if ( listener != null ) {
    listenerList.removeElement( listener );
    // Note: Since XML works with 1.1, this example uses Vector.
    // If coding for 1.2 or later, though, I'd use this instead:
    // private List listenerList = new LinkedList();
    // The operations on the List are then add(), remove() and
    // iteration, via:
    // Iterator it = listenerList.iterator();
    // while ( it.hasNext() ) {
    // TreeModelListener listener = (TreeModelListener) it.next();
    * Invoke these methods to inform listeners of changes.
    * (Not needed for this example.)
    * Methods taken from TreeModelSupport class described at
    * http://java.sun.com/products/jfc/tsc/articles/jtree/index.html
    * That architecture (produced by Tom Santos and Steve Wilson)
    * is more elegant. I just hacked 'em in here so they are
    * immediately at hand.
    public void fireTreeNodesChanged( TreeModelEvent e ) {
    Enumeration listeners = listenerList.elements();
    while ( listeners.hasMoreElements() ) {
    TreeModelListener listener =
    (TreeModelListener) listeners.nextElement();
    listener.treeNodesChanged( e );
    public void fireTreeNodesInserted( TreeModelEvent e ) {
    Enumeration listeners = listenerList.elements();
    while ( listeners.hasMoreElements() ) {
    TreeModelListener listener =
    (TreeModelListener) listeners.nextElement();
    listener.treeNodesInserted( e );
    public void fireTreeNodesRemoved( TreeModelEvent e ) {
    Enumeration listeners = listenerList.elements();
    while ( listeners.hasMoreElements() ) {
    TreeModelListener listener =
    (TreeModelListener) listeners.nextElement();
    listener.treeNodesRemoved( e );
    public void fireTreeStructureChanged( TreeModelEvent e ) {
    Enumeration listeners = listenerList.elements();
    while ( listeners.hasMoreElements() ) {
    TreeModelListener listener =
    (TreeModelListener) listeners.nextElement();
    listener.treeStructureChanged( e );
    }

    DocumentBuilderFactory can be configured to ignore white space.
    http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilderFactory.html#setIgnoringElementContentWhitespace(boolean)

  • How to Remove a Node from JTree?

    I want to remove a node from a JTree but the node may or maynot be visible.
    My method takes a String which is the name of the node.
    The nodes im using are DefaultMutableTreeNode
    This is my code so far but it doesnt work.
    public void removePerson(String pName)
              TreePath node = tree.getNextMatch(pName,0,Position.Bias.Forward);
              tree.expandPath(node);
              tree.removeSelectionPath(node);
    }Any Suggestions or ways which i could achive this?
    Thank you,

    I don't think removeSelectionPath is what you want to use.
    These should help:
    [http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html#removeNodeFromParent(javax.swing.tree.MutableTreeNode)|http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html#removeNodeFromParent(javax.swing.tree.MutableTreeNode)]
    [http://www.roseindia.net/java/example/java/swing/RemoveNodes.shtml|http://www.roseindia.net/java/example/java/swing/RemoveNodes.shtml]

Maybe you are looking for