JTree (TreeModel) vs (TreeNode)

hellow,
I've got some troubles with a tree-view of my data model: I've created my own TreeModel, implemented the necessary methods, ...
Now, when I try to display the JTree with the TreeNode parameter (I parse the whole data tree) it works perfectly, but when I'm trying the TreeModel parameter, it only shows the root node (I tried "treeStructureChanged (event)" without result).
Does someone know what I might be forgetting ?
Can I add a treenodes manually (might give me a clue what I'm doing wrong in my implementation) ?
thx alot,
Jerry

public class X
static public TreeNode parseDataModel () { ... }
// parseDataModel() returns the tree root node.
tree = new JTree(parseDataModel());
treeView = new JScrollPane(tree);
frame.getContentPane().add(treeView, BorderLayout.WEST);
=> this works fine
public class MyTreeModel implements TreeModel { ... }
MyTreeModel mtm = new MyTreeModel();
JTree jTree = new JTree (mtm);
treeView = new JScrollPane(jTree);
frame.getContentPane().add(treeView, BorderLayout.WEST);
=> only shows the root node (double-clicking it has no effect; it has no 'folder' icon)

Similar Messages

  • JTree & TreeModel

    Hi,
    I have created a TreeModel with my own unique object array.
    When i get a path component on the tree, it returns one of my unique objects.
    So they are not of type MutableTreeNode.
    That's all great!
    Now, if i want to add or remove a node on the tree what is the approach i should use?
    I am thinking i should find the parent in my array, update it's children and tell the tree that it needs to update itself.
    Is this correct?
    Any pointers would be of great benefit.
    Thanks,
    Dave

    I don't know what you need to do for your objects. With regard to your original post -- which I interpreted as asking how to get the view changed to reflect changes in the model -- the fact is that the JTree will attach itself as a listener to your tree model, so if the tree model needs to tell the JTree about some change in the model's tree structure, then the obvious way to do that is to send the appropriate messages to that listener.
    I also don't have any recommendations about how you should maintain your model, except to say that when you change something in your model, you do need to notify all its listeners that you made that change.

  • JTree Nimbus selection treeNode

    I made a jtree with a custom TreeCellRenderer. The leaf nodes are a jpanel with a checkbox in and JPanel. The problem now is that when you select a tree node, there is a selection color box beside the jpanel.
    Here is a sscce:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTree;
    import javax.swing.UIManager;
    import javax.swing.UIManager.LookAndFeelInfo;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    public class Users {
        private static JFrame frame;
        private static JPanel usersPanel;
        private JTree usersTree;
        public Users(){
            usersPanel = new JPanel();
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Gebruikers");
            DefaultMutableTreeNode willie = new DefaultMutableTreeNode("Willie");
            DefaultMutableTreeNode Anna = new DefaultMutableTreeNode("Anna");
            rootNode.add(willie);
            rootNode.add(Anna);
            usersTree = new JTree(rootNode);
            myTreeWithCheckBoxRenderer renderer = new myTreeWithCheckBoxRenderer();
            usersTree.setCellRenderer(renderer);
            usersTree.setRootVisible(true);
            usersTree.setEditable(false);
            usersTree.setOpaque(false);
            usersPanel.add(usersTree);
        class myTreeWithCheckBoxRenderer extends DefaultTreeCellRenderer {
            DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
            JPanel panel;
            JCheckBox checkBox;
            JLabel label;
            public myTreeWithCheckBoxRenderer() {
                checkBox = new JCheckBox();
                label = new JLabel("Gebruikers");
                panel = new JPanel(new BorderLayout());
                panel.add(checkBox, BorderLayout.WEST);
                panel.add(label, BorderLayout.EAST);
                panel.setBackground(Color.red);
            @Override
            public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                Component returnValue;
                if(!leaf){
                    renderer.setBackgroundSelectionColor(null);
                    renderer.setText("Gebruikers");
                    returnValue = renderer;
                else{
                    if(hasFocus){
                        panel.setBackground(Color.blue);
                    returnValue = panel;
                return returnValue;
        private static void createAndShowGUI(){
            new Users();
            frame = new JFrame("Tree");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(usersPanel);
            frame.pack();
            frame.setPreferredSize(new Dimension(800, 600));
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
         public static void main (String[] args){
            try {
                for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        UIManager.setLookAndFeel(info.getClassName());
                        break;
            } catch (UnsupportedLookAndFeelException e) {
                // handle exception
            } catch (ClassNotFoundException e) {
                // handle exception
            } catch (InstantiationException e) {
                // handle exception
            } catch (IllegalAccessException e) {
                // handle exception
            javax.swing.SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run(){
                    createAndShowGUI();
    }I tried using a DefaultTreeCellRenderer and use the setBackgroundSelectionColor() method to null, but it doesn't change anything. Also setting the background of the JPanel to null doesn't make a change when you check with (if(hasFocus)). However I have the impression that nimbus is causing the problem, because if you comment the nimbus part out, you don't have the selection box anymore.
    Does anyone has an idea to solve this?
    Edited by: Kligham on 30-aug-2010 19:25

    Kligham wrote:
    Thank you very much!You're welcome.
    Kligham wrote:
    Problem solved. So since this cell background rendering is a Nimbus "feature", can I assume that the "not displaying of angled lines" also is a Nimbus "feature". Since the JTree tutorial says this should do the trick:
    usersTree.putClientProperty("JTree.lineStyle", "Angled");So I probably have to override it the same way, so I was wondering how you know what UIDefaults there are?Well, "JTree.lineStyle" is actually a client property and not a UIDefaults property. In other words, "JTree.lineStyle" is on the same logical level as "Nimbus.Overrides". Unfortunately, there is no way to determine which client properties a component or a component UI implementation supports except carefully examining its source code. javax.swing.plaf.synth.SynthTreeUI (the Nimbus TreeUI implementation) doesn't seem to support any client properties. It might be handled somewhere else, though.
    As an alternative to using "JTree.lineStyle", you could try to use a backgroundPainter that draws angle lines instead of the "do nothing" painter I suggested.
    To determine which UIDefaults properties are available for a given LaF implementation, you can iterate over the UIDefaults' entrySet (UIDefaults is a subclass of Hashtable). For Nimbus specifically, Jasper Potts already did that. See the [corresponding blog entry|http://www.jasperpotts.com/blog/2008/08/nimbus-uimanager-uidefaults/] and [Nimbus UIDefaults Properties List|http://jasperpotts.com/blogfiles/nimbusdefaults/nimbus.html]

  • 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.

  • Help needed redrawing a JTree

    Hi,
    I'm writing a simple Swing program to examine the entries in a JAR file as a JTree. It is not meant to be professional grade, it's simply for my own fun.
    I have the program so that it displays a Window with a Menus. When the user chooses a JAR file, the program opens the JAR file, reads the entries in the file, and builds a DefaultTreeModel for the entries in the JAR file. Then, it builds a JTree from the DefaultTreeModel.
    The program works great, except, once the tree is created, I don't know how to force Swing to redraw the JFrame.
    Can someone please tell me what I'm doing wrong?
    The code is as follows:
    <pre>
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.io.*;
    import java.util.jar.*;
    import java.util.*;
    * <p>This class is used to display the contents of a JAR file.
    * The entries of the JAR file will be displayed in Swing Tree.
    * @version 1.0
    * @author Kevin Yetman
    public class JarFileTree
    * <p>This method is used to display the GUI.
    public static void main(String[] args)
    {  JFrame frame=new JarTreeFrame();
    frame.show();
    * <p>This class is used to define the javax.swing.JFrame based object that
    * will contain the tree from the JAR file.
    class JarTreeFrame extends JFrame implements ActionListener
    private JTree tree;
    private DefaultTreeModel treeModel;
    private DefaultMutableTreeNode root;
    private JScrollPane scrollPane;
    * <P>This constructor is used create and display the frame.
    public JarTreeFrame()
    {  setTitle("JAR Viewer");
    setSize(800, 600);
    addWindowListener(new WindowAdapter()
    {  public void windowClosing(WindowEvent e)
    {  System.exit(0);
    JMenuBar menuBar=setupMenuBar();
    setJMenuBar(menuBar);
    root = new DefaultMutableTreeNode("No file selected yet.");
    treeModel=new DefaultTreeModel(root);
    tree = new JTree(treeModel);
    scrollPane=new JScrollPane(tree);
    Container contentPane=getContentPane();
    contentPane.add(scrollPane);
    public void processString(String currentEntry, DefaultMutableTreeNode currentNode, DefaultTreeModel treeModel)
    if( currentEntry.length()==0 )
    {  return;
    int slashPos=currentEntry.indexOf('/');
    String currentToken="";
    String remainingPartOfCurrentEntry="";
    if( slashPos!=-1 )
    {  currentToken=currentEntry.substring(0, slashPos);
    remainingPartOfCurrentEntry=currentEntry.substring(slashPos+1, currentEntry.length());
    else
    {  currentToken=currentEntry;
    boolean childFound=false;
    for(Enumeration e=currentNode.children(); e.hasMoreElements(); )
    DefaultMutableTreeNode currentChild=(DefaultMutableTreeNode)e.nextElement();
    if( currentChild.toString().equals(currentToken) )
    processString(remainingPartOfCurrentEntry, currentChild, treeModel);
    childFound=true;
    if( !childFound )
    DefaultMutableTreeNode newChild=new DefaultMutableTreeNode(currentToken);
    treeModel.insertNodeInto(newChild, currentNode, currentNode.getChildCount());
    protected JMenuBar setupMenuBar()
    JMenuBar menuBar=new JMenuBar();
    JMenu helpMenu =new JMenu("Help");
    JMenuItem aboutItem=new JMenuItem("About");
    aboutItem.setActionCommand("HelpAbout");
    aboutItem.addActionListener(this);
    helpMenu.add(aboutItem);
    JMenu fileMenu = new JMenu("File");
    JMenuItem openItem=new JMenuItem("Open");
    openItem.setActionCommand("FileOpen");
    openItem.addActionListener(this);
    JMenuItem exitItem=new JMenuItem("Exit");
    exitItem.addActionListener( new ActionListener()
    {  public void actionPerformed(ActionEvent evt)
    { System.exit(0);
    fileMenu.add(openItem);
    fileMenu.add(exitItem);
    menuBar.add(fileMenu);
    menuBar.add(helpMenu);
    return menuBar;
    public void setupTree(String fileName)
    try
    JarFile jarFile=new JarFile(new File(fileName));
    for(Enumeration e=jarFile.entries(); e.hasMoreElements(); )
    String currentEntry=(e.nextElement().toString()).trim();
    processString(currentEntry, root, treeModel);
    DefaultMutableTreeNode lastLeaf=root.getLastLeaf();
    TreePath path=new TreePath(treeModel.getPathToRoot(lastLeaf));
    tree.makeVisible(path);
    catch(IOException e)
    {  JOptionPane.showMessageDialog(this, "ERROR: " + e.toString());
    public void actionPerformed(ActionEvent evt)
    if(evt.getActionCommand().equals("FileOpen"))
    FileOpenSaveAs fosa=new FileOpenSaveAs(this, true);
    if(fosa.approveOptionClicked())
    String fileName=fosa.getSelectedFile();
    fileName+=".jar";
    setupTree(fileName);
    Container contentPane=getContentPane();
    contentPane.removeAll();
    contentPane.add(new JScrollPane(tree));
    contentPane.repaint();
    if(evt.getActionCommand().equals("HelpAbout"))
    {  JOptionPane.showMessageDialog(this, "JAR Viewer Version 1.0\nKevin Yetman");
    // FileOpenSaveAs.java
    // Author: Kevin Yetman
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.event.*;
    // this class handles the display of the
    // File Open or File Save As box.
    public class FileOpenSaveAs {
    // the constructor takes one argument, a
    // boolean which if true opens the File Open
    // box. If false it opens the save as box.
    public FileOpenSaveAs(JFrame baseWindow, boolean fileOpenBox) {
    // initailze the result varialbe
    result=-1;
    // store the value of the fileOpenBox.
    openBox=fileOpenBox;
    // initialize the fileNameSelected string.
    fileNameSelected=new String();
    // first build a JFileChooser.
    JFileChooser fc=new JFileChooser();
    // next tell the file chooser to look in the
    // current directory.
    fc.setCurrentDirectory(new File(CURRENT_DIRECTORY));
    // if the file open box is true, display the file open box.
    // otherwise, display the file save as box.
    if( fileOpenBox ) {
    fc.setDialogTitle(OPEN_TITLE);
    displayBox(baseWindow, fc);
    else {
    fc.setDialogTitle(SAVE_AS_TITLE);
    displayBox(baseWindow, fc);
    // the constructor takes one argument, a
    // boolean which if true opens the File Open
    // box. If false it opens the save as box.
    public FileOpenSaveAs(JDialog baseWindow, boolean fileOpenBox) {
    // initailze the result varialbe
    result=-1;
    // store the value of the fileOpenBox.
    openBox=fileOpenBox;
    // initialize the fileNameSelected string.
    fileNameSelected=new String();
    // first build a JFileChooser.
    JFileChooser fc=new JFileChooser();
    // next tell the file chooser to look in the
    // current directory.
    fc.setCurrentDirectory(new File(CURRENT_DIRECTORY));
    // if the file open box is true, display the file open box.
    // otherwise, display the file save as box.
    if( fileOpenBox ) {
    fc.setDialogTitle(OPEN_TITLE);
    displayBox(baseWindow, fc);
    else {
    fc.setDialogTitle(SAVE_AS_TITLE);
    displayBox(baseWindow, fc);
    // this method displays the File Open box on the base window.
    public void displayBox(JFrame baseWindow, JFileChooser fc) {
    // display the file open box and get the result.
    result=-1;
    if( openBox==true ) {
    result=fc.showOpenDialog(baseWindow);
    else {
    result=fc.showSaveDialog(baseWindow);
    // get the file name.
    if( approveOptionClicked() ) {
    fileNameSelected=fc.getName(fc.getSelectedFile());
    else {
    fileNameSelected="";
    // this method displays the File Open box on the base window.
    public void displayBox(JDialog baseWindow, JFileChooser fc) {
    // display the file open box and get the result.
    result=-1;
    if( openBox==true ) {
    result=fc.showOpenDialog(baseWindow);
    else {
    result=fc.showSaveDialog(baseWindow);
    // get the file name.
    if( approveOptionClicked() ) {
    fileNameSelected=fc.getName(fc.getSelectedFile());
    else {
    fileNameSelected="";
    // check to see if the result is APPROVE_OPTION. If so, we
    // will return true.
    public boolean approveOptionClicked() {
    return (result == JFileChooser.APPROVE_OPTION );
    // get the file name chosen by the user.
    public String getSelectedFile() {
    return fileNameSelected;
    // private attributes for this class.
    private boolean openBox;
    private static final String CURRENT_DIRECTORY=".";
    private static final String SAVE_AS_TITLE="Save As";
    private static final String OPEN_TITLE="Open";
    private int result;
    private String fileNameSelected;
    </pre>
    Thanks!
    Kevin Yetman

    Without looking at all your code, I would suggest that you only redraw the part of the tree that changes (addition or deletion of nodes). To do this, you can call a method of DefaultTreeModel, nodeStructureChanged(TreeNode nodeThatChanged). This fires the appropriate event which in turn causes the node and only its descendents to be redrawn. Good luck.
    -Matt

  • Help with building a JTree using tree node and node renderers

    Hi,
    I am having a few problems with JTree's. basically I want to build JTree from a web spider. The webspide searches a website checking links and stores the current url that is being processed as a string in the variable msg. I wan to use this variable to build a JTree in a new class and then add it to my GUI. I have created a tree node class and a renderer node class, these classes are built fine. can someone point me in the direction for actually using these to build my tree in a seperate class and then displaying it in a GUI class?
    *nodeRenderer.java
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import java.net.*;
    public class nodeRenderer extends DefaultTreeCellRenderer
                                       implements TreeCellRenderer
    public static Icon icon= null;
    public nodeRenderer() {
    icon = new ImageIcon(getClass().getResource("icon.gif"));
    public Component getTreeCellRendererComponent(
    JTree tree,
    Object value,
    boolean sel,
    boolean expanded,
    boolean leaf,
    int row,
    boolean hasFocus) {
    super.getTreeCellRendererComponent(
    tree, value, sel,
    expanded, leaf, row,
    hasFocus);
    treeNode node = (treeNode)(((DefaultMutableTreeNode)value).getUserObject());
    if(icon != null) // set a custom icon
    setOpenIcon(icon);
    setClosedIcon(icon);
    setLeafIcon(icon);
         return this;
    *treeNode.java
    *this is the class to represent a node
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.*;
    import java.net.*;
    * Class used to hold information about a web site that has
    * been searched by the spider class
    public class treeNode
    *Url from the WebSpiderController Class
    *that is currently being processed
    public String msg;
    treeNode(String urlText)
         msg = urlText;
    String getUrlText()
         return msg;
    //gui.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class gui extends JFrame implements Runnable
         *declare variable, boolean
         *thread, a object and a center
         *pane
         protected URL urlInput;
         protected Thread bgThread;
         protected boolean run = false;
         protected WebSpider webSpider;
         public gui()
              *create the gui here
              setTitle("Testing Tool");
         setSize(600,600);
         //add Buttons to the tool bar
         start.setText("Start");
         start.setActionCommand("Start");
         toolBar.add(start);
         ButtonListener startListener = new ButtonListener();
              start.addActionListener(startListener);
              cancel.setText("Cancel");
         cancel.setActionCommand("Cancel");
         toolBar.add(cancel);
         ButtonListener cancelListener = new ButtonListener();
              cancel.addActionListener(cancelListener);
              close.setText("Close");
         close.setActionCommand("Close");
         toolBar.add(close);
         ButtonListener closeListener = new ButtonListener();
              close.addActionListener(closeListener);
              //creat a simple form
              urlLabel.setText("Enter URL:");
              urlLabel.setBounds(100,36,288,24);
              formTab.add(urlLabel);
              url.setBounds(170,36,288,24);
              formTab.add(url);
              current.setText("Currently Processing: ");
              current.setBounds(100,80,288,24);
              formTab.add(current);
         //add scroll bars to the error messages screen and website structure
         errorPane.setAutoscrolls(true);
         errorPane.setHorizontalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
         errorPane.setVerticalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
         errorPane.setOpaque(true);
         errorTab.add(errorPane);
         errorPane.setBounds(0,0,580,490);
         errorText.setEditable(false);
         errorPane.getViewport().add(errorText);
         errorText.setBounds(0,0,600,550);
         treePane.setAutoscrolls(true);
         treePane.setHorizontalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
         treePane.setVerticalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
         treePane.setOpaque(true);
         treeTab.add(treePane);
         treePane.setBounds(0,0,580,490);
         treeText.setEditable(false);
         treePane.getViewport().add(treeText);
         treeText.setBounds(0,0,600,550);
         //create the tabbed window           
    centerPane.setBorder(new javax.swing.border.EtchedBorder());
    formTab.setLayout(null);
    errorTab.setLayout(null);
    treeTab.setLayout(null);
    centerPane.addTab("Search Parameters", formTab);
    centerPane.addTab("Error Messages", errorTab);
    centerPane.addTab("Website Structure", treeTab);
              //add the tool bar and tabbed pane
              getContentPane().add(toolBar, java.awt.BorderLayout.NORTH);
    getContentPane().add(centerPane, java.awt.BorderLayout.CENTER);                    
              *create the tool bar pane, a center pane, add the buttons,
              *labels, tabs, a text field for user input here
              javax.swing.JPanel toolBar = new javax.swing.JPanel();
              javax.swing.JButton start = new javax.swing.JButton();
              javax.swing.JButton cancel = new javax.swing.JButton();
              javax.swing.JButton close = new javax.swing.JButton();      
              javax.swing.JTabbedPane centerPane = new javax.swing.JTabbedPane();
              javax.swing.JPanel formTab = new javax.swing.JPanel();
              javax.swing.JLabel urlLabel = new javax.swing.JLabel();
              javax.swing.JLabel current = new javax.swing.JLabel();
              javax.swing.JTextField url = new javax.swing.JTextField();
              javax.swing.JPanel errorTab = new javax.swing.JPanel();
              javax.swing.JTextArea errorText = new javax.swing.JTextArea();
              javax.swing.JScrollPane errorPane = new javax.swing.JScrollPane();
              javax.swing.JPanel treeTab = new javax.swing.JPanel();
              javax.swing.JTextArea treeText = new javax.swing.JTextArea();
              javax.swing.JScrollPane treePane = new javax.swing.JScrollPane();
              javax.swing.JTree searchTree = new javax.swing.JTree();
              *show the gui
              public static void main(String args[])
              (new gui()).setVisible(true);
         *listen for the button presses and set the
         *boolean flag depending on which button is pressed
         class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event)
                   Object object = event.getSource();
                   if (object == start)
                        run = true;
                        startActionPerformed(event);
                   if (object == cancel)
                        run = false;
                        startActionPerformed(event);
                   if (object == close)
                        System.exit(0);
         *this method is called when the start or
         *cancel button is pressed.
         void startActionPerformed (ActionEvent event)
              if (run == true && bgThread == null)
                   bgThread = new Thread(this);
                   bgThread.start();
              if (run == false && bgThread != null)
                   webSpider.cancel();
         *this mehtod will start the background thred.
         *the background thread is required so that the
         *GUI is still displayed
         public void run()
              try
                   webSpider = new WebSpider(this);
                   webSpider.clear();
                   urlInput = new URL(url.getText());
                   webSpider.addURL(urlInput);
                   webSpider.run();
                   bgThread=null;
              catch (MalformedURLException e)
                   addressError addErr = new addressError();
                   addErr.addMsg = "URL ERROR - PLEASE CHECK";
                   SwingUtilities.invokeLater(addErr);
              *this method is called by the web spider
              *once a url is found. Validation of navigation
              *happens here.
              public boolean urlFound(URL urlInput,URL url)
                   CurrentlyProcessing pro = new CurrentlyProcessing();
              pro.msg = url.toString();
              SwingUtilities.invokeLater(pro);
              if (!testLink(url))
                        navigationError navErr = new navigationError();
                        navErr.navMsg = "Broken Link "+url+" caused on "+urlInput+"\n";
                        return false;
              if (!url.getHost().equalsIgnoreCase(urlInput.getHost()))
                   return false;
              else
                   return true;
              *this method is called internally to check
         *that a link works
              protected boolean testLink(URL url)
              try
                   URLConnection connection = url.openConnection();
                   connection.connect();
                   return true;
              catch (IOException e)
                   return false;
         *this method is called when an error is
         *found.
              public void URLError(URL url)
              *this method is called when an email
              *address is found
              public void emailFound(String email)
              /*this method will update any errors found inc
              *address errors and broken links
              class addressError implements Runnable
                   public String addMsg;
                   public void run()
                        errorText.append(addMsg);
                        current.setText("Currently Processing: "+ addMsg);
              class navigationError implements Runnable
                   public String navMsg;
                   public void run()
                        errorText.append(navMsg);
              *this method will update the currently
              *processing field on the GUI
              class CurrentlyProcessing implements Runnable
              public String msg;
              public void run()
                   current.setText("Currently Processing: " + msg );
    //webspider.java
    import java.util.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.tree.*;
    import javax.swing.*;
    *this class implements the spider.
    public class WebSpider extends HTMLEditorKit
         *make a collection of the URL's
         protected Collection urlErrors = new ArrayList(3);
         protected Collection urlsWaiting = new ArrayList(3);
         protected Collection urlsProcessed = new ArrayList(3);
         //report URL's to this class
         protected gui report;
         *this flag will indicate whether the process
         *is to be cancelled
         protected boolean cancel = false;
         *The constructor
         *report the urls to the wui class
         public WebSpider(gui report)
         this.report = report;
         *get the urls from the above declared
         *collections
         public Collection getUrlErrors()
         return urlErrors;
         public Collection getUrlsWaiting()
         return urlsWaiting;
         public Collection getUrlsProcessed()
         return urlsProcessed;
         * Clear all of the collections.
         public void clear()
         getUrlErrors().clear();
         getUrlsWaiting().clear();
         getUrlsProcessed().clear();
         *Set a flag that will cause the begin
         *method to return before it is done.
         public void cancel()
         cancel = true;
         *add the entered url for porcessing
         public void addURL(URL url)
         if (getUrlsWaiting().contains(url))
              return;
         if (getUrlErrors().contains(url))
              return;
         if (getUrlsProcessed().contains(url))
              return;
         /*WRITE TO LOG FILE*/
         log("Adding to workload: " + url );
         getUrlsWaiting().add(url);
         *process a url
         public void processURL(URL url)
         try
              /*WRITE TO LOGFILE*/
              log("Processing: " + url );
              // get the URL's contents
              URLConnection connection = url.openConnection();
              if ((connection.getContentType()!=null) &&
         !connection.getContentType().toLowerCase().startsWith("text/"))
              getUrlsWaiting().remove(url);
              getUrlsProcessed().add(url);
              log("Not processing because content type is: " +
         connection.getContentType() );
                   return;
         // read the URL
         InputStream is = connection.getInputStream();
         Reader r = new InputStreamReader(is);
         // parse the URL
         HTMLEditorKit.Parser parse = new HTMLParse().getParser();
         parse.parse(r,new Parser(url),true);
    catch (IOException e)
         getUrlsWaiting().remove(url);
         getUrlErrors().add(url);
         log("Error: " + url );
         report.URLError(url);
         return;
    // mark URL as complete
    getUrlsWaiting().remove(url);
    getUrlsProcessed().add(url);
    log("Complete: " + url );
    *start the spider
    public void run()
    cancel = false;
    while (!getUrlsWaiting().isEmpty() && !cancel)
         Object list[] = getUrlsWaiting().toArray();
         for (int i=0;(i<list.length)&&!cancel;i++)
         processURL((URL)list);
    * A HTML parser callback used by this class to detect links
    protected class Parser extends HTMLEditorKit.ParserCallback
    protected URL urlInput;
    public Parser(URL urlInput)
    this.urlInput = urlInput;
    public void handleSimpleTag(HTML.Tag t,MutableAttributeSet a,int pos)
    String href = (String)a.getAttribute(HTML.Attribute.HREF);
    if((href==null) && (t==HTML.Tag.FRAME))
    href = (String)a.getAttribute(HTML.Attribute.SRC);
    if (href==null)
    return;
    int i = href.indexOf('#');
    if (i!=-1)
    href = href.substring(0,i);
    if (href.toLowerCase().startsWith("mailto:"))
    report.emailFound(href);
    return;
    handleLink(urlInput,href);
    public void handleStartTag(HTML.Tag t,MutableAttributeSet a,int pos)
    handleSimpleTag(t,a,pos); // handle the same way
    protected void handleLink(URL urlInput,String str)
    try
         URL url = new URL(urlInput,str);
    if (report.urlFound(urlInput,url))
    addURL(url);
    catch (MalformedURLException e)
    log("Found malformed URL: " + str);
    *log the information of the spider
    public void log(String entry)
    System.out.println( (new Date()) + ":" + entry );
    I have a seperate class for parseing the HTML. Any help would be greatly appreciated
    mrv

    Hi Sorry to be a pain again,
    I have re worked the gui class so it looks like this now:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class gui extends JFrame implements Runnable
         *declare variable, boolean
         *thread, a object and a center
         *pane
         protected URL urlInput;
         protected Thread bgThread;
         protected boolean run = false;
         protected WebSpider webSpider;
         public String msgInfo;
         public String brokenUrl;
         public String goodUrl;
         public String deadUrl;
         protected DefaultMutableTreeNode rootNode;
    protected DefaultTreeModel treeModel;
         public gui()
              *create the gui here
              setTitle("Testing Tool");
         setSize(600,600);
         //add Buttons to the tool bar
         start.setText("Start");
         start.setActionCommand("Start");
         toolBar.add(start);
         ButtonListener startListener = new ButtonListener();
              start.addActionListener(startListener);
              cancel.setText("Cancel");
         cancel.setActionCommand("Cancel");
         toolBar.add(cancel);
         ButtonListener cancelListener = new ButtonListener();
              cancel.addActionListener(cancelListener);
              close.setText("Close");
         close.setActionCommand("Close");
         toolBar.add(close);
         ButtonListener closeListener = new ButtonListener();
              close.addActionListener(closeListener);
              //creat a simple form
              urlLabel.setText("Enter URL:");
              urlLabel.setBounds(100,36,288,24);
              formTab.add(urlLabel);
              url.setBounds(170,36,288,24);
              formTab.add(url);
              current.setText("Currently Processing: ");
              current.setBounds(100,80,288,24);
              formTab.add(current);
         //add scroll bars to the error messages screen and website structure
         errorPane.setAutoscrolls(true);
         errorPane.setHorizontalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
         errorPane.setVerticalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
         errorPane.setOpaque(true);
         errorTab.add(errorPane);
         errorPane.setBounds(0,0,580,490);
         errorText.setEditable(false);
         errorPane.getViewport().add(errorText);
         errorText.setBounds(0,0,600,550);
         treePane.setAutoscrolls(true);
         treePane.setHorizontalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
         treePane.setVerticalScrollBarPolicy(javax.swing.
         ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
         treePane.setOpaque(true);
         treeTab.add(treePane);
         treePane.setBounds(0,0,580,490);
         treeText.setEditable(false);
         treePane.getViewport().add(treeText);
         treeText.setBounds(0,0,600,550);
         //JTree
         // NEW CODE
         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);
         treeText.add(tree);
         //create the tabbed window           
    centerPane.setBorder(new javax.swing.border.EtchedBorder());
    formTab.setLayout(null);
    errorTab.setLayout(null);
    treeTab.setLayout(null);
    centerPane.addTab("Search Parameters", formTab);
    centerPane.addTab("Error Messages", errorTab);
    centerPane.addTab("Website Structure", treeTab);
              //add the tool bar and tabbed pane
              getContentPane().add(toolBar, java.awt.BorderLayout.NORTH);
    getContentPane().add(centerPane, java.awt.BorderLayout.CENTER);     
              *create the tool bar pane, a center pane, add the buttons,
              *labels, tabs, a text field for user input here
              javax.swing.JPanel toolBar = new javax.swing.JPanel();
              javax.swing.JButton start = new javax.swing.JButton();
              javax.swing.JButton cancel = new javax.swing.JButton();
              javax.swing.JButton close = new javax.swing.JButton();      
              javax.swing.JTabbedPane centerPane = new javax.swing.JTabbedPane();
              javax.swing.JPanel formTab = new javax.swing.JPanel();
              javax.swing.JLabel urlLabel = new javax.swing.JLabel();
              javax.swing.JLabel current = new javax.swing.JLabel();
              javax.swing.JTextField url = new javax.swing.JTextField();
              javax.swing.JPanel errorTab = new javax.swing.JPanel();
              javax.swing.JTextArea errorText = new javax.swing.JTextArea();
              javax.swing.JScrollPane errorPane = new javax.swing.JScrollPane();
              javax.swing.JPanel treeTab = new javax.swing.JPanel();
              javax.swing.JTextArea treeText = new javax.swing.JTextArea();
              javax.swing.JScrollPane treePane = new javax.swing.JScrollPane();
              javax.swing.JTree tree = new javax.swing.JTree();
              *show the gui
              public static void main(String args[])
              (new gui()).setVisible(true);
         *listen for the button presses and set the
         *boolean flag depending on which button is pressed
         class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event)
                   Object object = event.getSource();
                   if (object == start)
                        run = true;
                        startActionPerformed(event);
                   if (object == cancel)
                        run = false;
                        startActionPerformed(event);
                   if (object == close)
                        System.exit(0);
         *this method is called when the start or
         *cancel button is pressed.
         void startActionPerformed (ActionEvent event)
              if (run == true && bgThread == null)
                   bgThread = new Thread(this);
                   bgThread.start();
                   //new line of code
                   treeText.addObject(msgInfo);
              if (run == false && bgThread != null)
                   webSpider.cancel();
         *this mehtod will start the background thred.
         *the background thread is required so that the
         *GUI is still displayed
         public void run()
              try
                   webSpider = new WebSpider(this);
                   webSpider.clear();
                   urlInput = new URL(url.getText());
                   webSpider.addURL(urlInput);
                   webSpider.run();
                   bgThread = null;
              catch (MalformedURLException e)
                   addressError addErr = new addressError();
                   addErr.addMsg = "URL ERROR - PLEASE CHECK";
                   SwingUtilities.invokeLater(addErr);
              *this method is called by the web spider
              *once a url is found. Validation of navigation
              *happens here.
              public boolean urlFound(URL urlInput,URL url)
                   CurrentlyProcessing pro = new CurrentlyProcessing();
              pro.msg = url.toString();
              SwingUtilities.invokeLater(pro);
              if (!testLink(url))
                        navigationError navErr = new navigationError();
                        navErr.navMsg = "Broken Link "+url+" caused on "+urlInput+"\n";
                        brokenUrl = url.toString();
                        return false;
              if (!url.getHost().equalsIgnoreCase(urlInput.getHost()))
                   return false;
              else
                   return true;
              *this method is returned if there is no link
              *on a web page, e.g. there us a dead end
              public void urlNotFound(URL urlInput)
                        deadEnd dEnd = new deadEnd();
                        dEnd.dEMsg = "No links on "+urlInput+"\n";
                        deadUrl = urlInput.toString();               
              *this method is called internally to check
         *that a link works
              protected boolean testLink(URL url)
              try
                   URLConnection connection = url.openConnection();
                   connection.connect();
                   goodUrl = url.toString();
                   return true;
              catch (IOException e)
                   return false;
         *this method is called when an error is
         *found.
              public void urlError(URL url)
              *this method is called when an email
              *address is found
              public void emailFound(String email)
              /*this method will update any errors found inc
              *address errors and broken links
              class addressError implements Runnable
                   public String addMsg;
                   public void run()
                        current.setText("Currently Processing: "+ addMsg);
                        errorText.append(addMsg);
              class navigationError implements Runnable
                   public String navMsg;
                   public void run()
                        errorText.append(navMsg);
              class deadEnd implements Runnable
                   public String dEMsg;
                   public void run()
                        errorText.append(dEMsg);
              *this method will update the currently
              *processing field on the GUI
              public class CurrentlyProcessing implements Runnable
                   public String msg;
              //new line
              public String msgInfo = msg;
              public void run()
                   current.setText("Currently Processing: " + msg );
         * NEW CODE
         * NEED THIS CODE SOMEWHERE
         * treeText.addObject(msgInfo);
         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());
         if (shouldBeVisible)
         tree.scrollPathToVisible(new TreePath(childNode.getPath()));
              return childNode;
         public class MyTreeModelListener implements TreeModelListener
              public void treeNodesChanged (TreeModelEvent e)
                   DefaultMutableTreeNode node;
                   node = (DefaultMutableTreeNode)
                   (e.getTreePath().getLastPathComponent());
                   try
                        int index = e.getChildIndices()[0];
                        node = (DefaultMutableTreeNode)
                        (node.getChildAt(index));
                   catch (NullPointerException exc)
              public void treeNodesInserted(TreeModelEvent e)
              public void treeStructureChanged(TreeModelEvent e)
              public void treeNodesRemoved(TreeModelEvent e)
    I beleive that this line of code is required:
    treeText.addObject(msgInfo);
    I have placed it where the action events start the spider, but i keep getting this error:
    cannot resolve symbol
    symbol : method addObject (java.lang.String)
    location: class javax.swing.JTextArea
    treeText.addObject(msgInfo);
    Also the jtree is not showing the window that I want it to and I am not too sure why. could you have a look to see why? i think it needs a fresh pair of eyes.
    Many thanks
    MrV

  • How to add a TreeNode using a path?

    When I doing my project, I get stuck on a portion of my GUI Coding.
    My code provide a path such as
    /Home/fsloke
    /Home/fsloke/directory1
    /Home/WorkHard
    /Home/WorkSmart
    /Home/WorkSmart/Dreamincode
    Currently my tree constructed as below:
    Home
    + fsloke
    ---+directory1
    + WorkHard
    + WorkSmart
    ---+ Dreamincode
    May I know how can I add a childNode called "TryHard" under WorkHard?
    Generally the path give is "/Home/WorkHard/TryHard".
    Don't worried I will split it to
    TreeNode Head ="Home"
    parentPath ="/Home/WorkHard";
    childNode name = "TryHard";
    Any clue?
    I search in net. All give me the solution when the user click on the tree Node. Then the code use , getSelectedPath() function.
    In my case my user not click on the Tree...
    Any advise and direction...
    Thanx...
    I like the DynamicTreeDemo coding from this website http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html

    you can use this method:
    addChildTo("WorkHard","TryHard");
    public void addChildTo(String parentObject, String child){
             TreePath parentPath = getTreePath(parentObject);
             if(parentPath != null){
                 DefaultMutableTreeNode parent = (DefaultMutableTreeNode)parentPath.getLastPathComponent();
                 treeModel.insertNodeInto(new DefaultMutableTreeNode(child), parent, parent.getChildCount());
    private TreePath getTreePath(String userObject) {
             java.util.Enumeration nodes = ( (DefaultMutableTreeNode) treeModel.getRoot()).
             preorderEnumeration();
             while (nodes.hasMoreElements()) {
                  DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodes.nextElement();
                  if (node.getUserObject().equals(userObject)){
                       return new TreePath(node.getPath());
             return null;
    }if you are using new DefaultMutableTreeNode("WorkHard"); , then the object name(WorkHard) should be unique , otherwise create node with your own object. Or alter the method what ever you need..
    edit:
    creation of jtree like
    DefaultMutableTreeNode top =
                new DefaultMutableTreeNode("The Java Series");
            createNodes(top);
            treeModel = new DefaultTreeModel(top);
            tree = new JTree(treeModel);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);ref:http://java.sun.com/docs/books/tutorial/uiswing/examples/components/TreeDemoProject/src/components/TreeDemo.java
    Edited by: david_david on Mar 19, 2008 10:15 AM

  • JTree with XML content expand/collapse problem

    Hello all,
    I'm having this very weird problem with a JTree I use to display the contents of an XML file. I use the DOM parser (and not JDOM since I want the application to run as an applet as well, and don't want to have any external libraries for the user to download) and have a custom TreeModel and TreeNode implementations to wrap the DOM nodes so that they are displayed by the JTree.
    I have also added a popup menu in the tree, for the user to be able to expand/collapse all nodes under the selected one (i.e. a recursive method).
    When expandAll is run, everything works fine and the children of the selected node are expanded (and their children and so on).
    However, after the expansion when I run the collapseAll function, even though the selected node collapses, when I re-expand it (manually not by expandAll) all of it's children are still fully open! Even if I collapse sub-elements of the node manually and then collapse this node and re-expand it, it "forgets" the state of it's children and shows them fully expanded.
    In other words once I use expandAll no matter what I do, the children of this node will be expanded (once I close it and re-open it).
    Also after running expandAll the behaviour(!) of the expanded nodes change: i have tree.setToggleClickCount(1); but on the expanded nodes I need to double-click to collapse them.
    I believe the problem is related to my implementations of TreeModel and TreeNode but after many-many hours of trying to figure out what's happening I'm desperate... Please help!
    Here's my code:
    public class XMLTreeNode implements TreeNode 
         //This class wraps a DOM node
        org.w3c.dom.Node domNode;
        protected boolean allowChildren;
        protected Vector children;
        //compressed view (#text).
         private static boolean compress = true;   
        // 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",
        static final int ELEMENT_TYPE =   1;
        static final int ATTR_TYPE =      2;
        static final int TEXT_TYPE =      3;
        static final int CDATA_TYPE =     4;
        static final int ENTITYREF_TYPE = 5;
        static final int ENTITY_TYPE =    6;
        static final int PROCINSTR_TYPE = 7;
        static final int COMMENT_TYPE =   8;
        static final int DOCUMENT_TYPE =  9;
        static final int DOCTYPE_TYPE =  10;
        static final int DOCFRAG_TYPE =  11;
        static final int NOTATION_TYPE = 12;
        // The list of elements to display in the tree
       static String[] treeElementNames = {
            "node",
      // Construct an Adapter node from a DOM node
      public XMLTreeNode(org.w3c.dom.Node node) {
        domNode = node;
      public String toString(){
           if (domNode.hasAttributes()){
                return domNode.getAttributes().getNamedItem("label").getNodeValue();
           }else return domNode.getNodeName();      
      public boolean isLeaf(){ 
           return (this.getChildCount()==0);
      boolean treeElement(String elementName) {
          for (int i=0; i<treeElementNames.length; i++) {
            if ( elementName.equals(treeElementNames)) return true;
    return false;
    public int getChildCount() {
         if (!compress) {   
    return domNode.getChildNodes().getLength();
    int count = 0;
    for (int i=0; i<domNode.getChildNodes().getLength(); i++) {
    org.w3c.dom.Node node = domNode.getChildNodes().item(i);
    if (node.getNodeType() == ELEMENT_TYPE
    && treeElement( node.getNodeName() ))
    // Note:
    // Have to check for proper type.
    // The DOCTYPE element also has the right name
    ++count;
    return count;
    public boolean getAllowsChildren() {
         // TODO Auto-generated method stub
         return true;
    public Enumeration children() {
         // TODO Auto-generated method stub
         return null;
    public TreeNode getParent() {
         // TODO Auto-generated method stub
         return null;
    public TreeNode getChildAt(int searchIndex) {
    org.w3c.dom.Node node =
    domNode.getChildNodes().item(searchIndex);
    if (compress) {
    // Return Nth displayable node
    int elementNodeIndex = 0;
    for (int i=0; i<domNode.getChildNodes().getLength(); i++) {
    node = domNode.getChildNodes().item(i);
    if (node.getNodeType() == ELEMENT_TYPE
    && treeElement( node.getNodeName() )
    && elementNodeIndex++ == searchIndex) {
    break;
    return new XMLTreeNode(node);
    public int getIndex(TreeNode tnode) {
         if (tnode== null) {
              throw new IllegalArgumentException("argument is null");
         XMLTreeNode child=(XMLTreeNode)tnode;
         int count = getChildCount();
         for (int i=0; i<count; i++) {
              XMLTreeNode n = (XMLTreeNode)this.getChildAt(i);
              if (child.domNode == n.domNode) return i;
         return -1; // Should never get here.
    public class XMLTreeModel2 extends DefaultTreeModel
         private Vector listenerList = new Vector();
         * This adapter converts the current Document (a DOM) into
         * a JTree model.
         private Document document;
         public XMLTreeModel2 (Document doc){
              super(new XMLTreeNode(doc));
              this.document=doc;
         public Object getRoot() {
              //System.err.println("Returning root: " +document);
              return new XMLTreeNode(document);
         public boolean isLeaf(Object aNode) {
              return ((XMLTreeNode)aNode).isLeaf();
         public int getChildCount(Object parent) {
              XMLTreeNode node = (XMLTreeNode) parent;
    return node.getChildCount();
         public Object getChild(Object parent, int index) {
    XMLTreeNode node = (XMLTreeNode) parent;
    return node.getChildAt(index);
         public int getIndexOfChild(Object parent, Object child) {
    if (parent==null || child==null )
         return -1;
              XMLTreeNode node = (XMLTreeNode) parent;
    return node.getIndex((XMLTreeNode) child);
         public void valueForPathChanged(TreePath path, Object newValue) {
    // Null. no changes
         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 );
         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 );
    The collapseAll, expandAll code (even though I m pretty sure that's not the problem since they work fine on a normal JTree):
        private void collapseAll(TreePath tp){
             if (tp==null) return;
             Object node=tp.getLastPathComponent();
             TreeModel model=tree.getModel();
             if (!model.isLeaf(node)){
                  tree.collapsePath(tp);
                  for (int i=0;i<model.getChildCount(node);i++){
                  //for (int i = node.childCount()-4;i>=0;i--){
                       collapseAll(tp.pathByAddingChild(model.getChild(node,i)));
                  tree.collapsePath(tp);
        private void expandAll(TreePath tp){
             if (tp==null) return;
             Object node=tp.getLastPathComponent();
             TreeModel model=tree.getModel();
             if (!model.isLeaf(node)){
                  tree.expandPath(tp);
                  for (int i=0;i<model.getChildCount(node);i++){
                  //for (int i = node.childCount()-4;i>=0;i--){
                       expandAll(tp.pathByAddingChild(model.getChild(node,i)));

    Hi,
    Iam not facing this problem. To CollapseAll, I do a tree.getModel().reload() which causes all nodes to get collapsed and remain so even if I reopen them manually.
    Hope this helps.
    cheers,
    vidyut

  • How to dislay a frame when i clck on the node or leaf on the JTree

    Hi All,
    Iam doing project on swing. In that iam doing with JTree. The Jtree is displaying on the left side of the splitpane .My problem is if i click on the nodes or leaf in the JTree one panel should be open in on the right side of the spltpane. Iam pasting the code.please can any body knows the solution please send me.
    regards
    sonali
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.BorderFactory;
    import javax.swing.border.*;
    import java.awt.event.*;
    import javax.swing.tree.*;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.tree.TreeSelectionModel;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import java.net.URL;
    import javax.swing.*;
    import java.io.IOException;
    import javax.swing.JEditorPane;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JFrame;
    import Test.Test1;
    public class JFrame1 extends javax.swing.JFrame {
    JScrollPane sp;
    JPanel topPanel;
    JPanel leftPanel;
    JPanel bottomPanel;
    JPanel rightPanel;
    Border b ;
    JTree tree;
    DefaultTreeModel treeModel;
         public JFrame1(){
              getContentPane().setLayout(null);
              setSize(405,305);
              setVisible(false);
              JPanel1.setLayout(null);
              getContentPane().add(JPanel1);
              JPanel1.setLayout(new GridLayout(1, 1));
              JPanel1.setBounds(0,0,405,305);
              JPanel1.add(JSplitPane1);
              JSplitPane1.setBounds(0,5,405,305);
              JSplitPane1.setContinuousLayout(false);
              topPanel = new JPanel();
              leftPanel = new JPanel();
              bottomPanel = new JPanel();
              topPanel.setLayout(new FlowLayout());
              leftPanel.setLayout(null);
              b = new EtchedBorder();
              leftPanel.setBorder(b);
              leftPanel.setBounds(0,0,300,305);
              bottomPanel.setLayout(new FlowLayout());
              rightPanel = new JPanel();
              rightPanel.setBounds(108, 0, 300, 305);
              JSplitPane1.setRightComponent(rightPanel);
              JSplitPane1.setLeftComponent(leftPanel);
              rightPanel.setLayout(null);
              topPanel.setBounds(0,0,305,25);
              b = new EtchedBorder(0);
              topPanel.setBorder(b);
              bottomPanel.setBounds(0,26,300,280);
              b = new BevelBorder(1, Color.black,Color.black);
              bottomPanel.setBorder(b);
              rightPanel.add(topPanel);
              rightPanel.add(bottomPanel);
              JSplitPane1.setDividerLocation(120);
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    DefaultMutableTreeNode subroot = new DefaultMutableTreeNode("SubRoot");
    DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
    DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");
    DefaultMutableTreeNode leaf3 = new DefaultMutableTreeNode("Leaf 3");
    DefaultMutableTreeNode subroot1 = new DefaultMutableTreeNode("SubRoot1");
    DefaultMutableTreeNode leaf11 = new DefaultMutableTreeNode("Leaf 11");
    DefaultMutableTreeNode leaf21 = new DefaultMutableTreeNode("Leaf 21");
    DefaultMutableTreeNode leaf31 = new DefaultMutableTreeNode("Leaf 31 skfjdsf sfjfdsl fslfkjdsfl sflkjaflksdfdslfjds lfsdlkfjdslk sdsdlkfjdsla fflkdasjfdslkjal");
    DefaultMutableTreeNode subroot2 = new DefaultMutableTreeNode("SubRoot2");
    DefaultMutableTreeNode leaf12 = new DefaultMutableTreeNode("Leaf 12");
    DefaultMutableTreeNode leaf22 = new DefaultMutableTreeNode("Leaf 22");
    DefaultMutableTreeNode leaf32 = new DefaultMutableTreeNode("Leaf 32");
    treeModel = new DefaultTreeModel(root);
    tree = new JTree(treeModel);
    treeModel.insertNodeInto(subroot, root, 0);
    treeModel.insertNodeInto(leaf1, subroot, 0);
    treeModel.insertNodeInto(leaf2, root, 1);
    treeModel.insertNodeInto(leaf3, root, 2);
    treeModel.insertNodeInto(subroot1, root, 3);
    treeModel.insertNodeInto(leaf11, subroot1, 0);
    treeModel.insertNodeInto(leaf21, subroot1, 1);
    treeModel.insertNodeInto(leaf31, subroot1, 2);
    treeModel.insertNodeInto(subroot2, root, 3);
    treeModel.insertNodeInto(leaf12, subroot2, 0);
    treeModel.insertNodeInto(leaf22, subroot2, 1);
    treeModel.insertNodeInto(leaf32, subroot2, 2);
    sp = new JScrollPane();
    sp.setBounds(0,0,300,305);
    sp.getViewport().add(tree);
    sp.setViewportBorder(BorderFactory.createRaisedBevelBorder());
    leftPanel.add(sp,BorderLayout.CENTER);
    //          SymPropertyChange lSymPropertyChange = new SymPropertyChange();
    //          JSplitPane1.addPropertyChangeListener(lSymPropertyChange);
              SymWindow aSymWindow = new SymWindow();
              this.addWindowListener(aSymWindow);
              SymComponent aSymComponent = new SymComponent();
              this.addComponentListener(aSymComponent);
         public JFrame1(String sTitle)
              this();
              setTitle(sTitle);
         public void setVisible(boolean b)
              if (b)
                   setLocation(50, 50);
              super.setVisible(b);
         static public void main(String args[])
              (new JFrame1()).setVisible(true);
         public void addNotify()
              Dimension size = getSize();
              super.addNotify();
              if (frameSizeAdjusted)
                   return;
              frameSizeAdjusted = false;
              Insets insets = getInsets();
              javax.swing.JMenuBar menuBar = getRootPane().getJMenuBar();
              int menuBarHeight = 0;
              if (menuBar != null)
                   menuBarHeight = menuBar.getPreferredSize().height;
              setSize(insets.left + insets.right + size.width, insets.top + insets.bottom + size.height + menuBarHeight);
         boolean frameSizeAdjusted = false;
         javax.swing.JPanel JPanel1 = new javax.swing.JPanel();
         javax.swing.JSplitPane JSplitPane1 = new javax.swing.JSplitPane();
         /*class SymPropertyChange implements java.beans.PropertyChangeListener{
              public void propertyChange(java.beans.PropertyChangeEvent event){
                   Object object = event.getSource();
                   if (object == JSplitPane1)
                        JSplitPane1_propertyChange(event);
    /*     void JSplitPane1_propertyChange(java.beans.PropertyChangeEvent event){
         System.out.println("!");
         sp.setSize((int)JSplitPane1.getLeftComponent().getBounds().getWidth()-2,(int)JSplitPane1.getLeftComponent().getBounds().getHeight()-2 );
         sp.repaint();
         tree.repaint();
         class SymWindow extends java.awt.event.WindowAdapter{
              public void windowActivated(java.awt.event.WindowEvent event){
                   Object object = event.getSource();
                   if (object == JFrame1.this)
                        JFrame1_windowActivated(event);
              public void windowIconified(java.awt.event.WindowEvent event){
                   Object object = event.getSource();
                   if (object == JFrame1.this)
                        JFrame1_windowIconified(event);
         void JFrame1_windowIconified(java.awt.event.WindowEvent event){
         void JFrame1_windowActivated(java.awt.event.WindowEvent event){
         class SymComponent extends java.awt.event.ComponentAdapter{
              public void componentShown(java.awt.event.ComponentEvent event){
                   Object object = event.getSource();
                   if (object == JFrame1.this)
                        JFrame1_componentShown(event);
              public void componentResized(java.awt.event.ComponentEvent event){
                   Object object = event.getSource();
                   if (object == JFrame1.this)
                        JFrame1_componentResized(event);
         void JFrame1_componentResized(java.awt.event.ComponentEvent event){
         System.out.println("!!");
              JPanel1.setSize(this.getContentPane().getMaximumSize());
              JSplitPane1.setSize((int)JPanel1.getMaximumSize().getWidth()-5,(int)JPanel1.getMaximumSize().getHeight()-5 );
              topPanel.setBounds(0, 0, rightPanel.getWidth()-3, 25);
              bottomPanel.setBounds(0,26,rightPanel.getWidth()-3,rightPanel.getHeight()-28);
              sp.setSize((int)leftPanel.getMaximumSize().getWidth(),(int)leftPanel.getMaximumSize().getHeight());
         sp.setAutoscrolls(true);
         //sp.setSize((int)JSplitPane1.getLeftComponent().getBounds().getWidth()-2,(int)JSplitPane1.getLeftComponent().getBounds().getHeight()-2 );
         sp.repaint();
         //sp.setSize((int)leftPanel.getSize().getWidth(),(int)leftPanel.getSize().getHeight() );
         void JFrame1_componentShown(java.awt.event.ComponentEvent event){
         System.out.println("!!!");
              JPanel1.setSize(this.getContentPane().getMaximumSize());
              JSplitPane1.setSize((int)JPanel1.getMaximumSize().getWidth()-5,(int)JPanel1.getMaximumSize().getHeight()-5 );
              topPanel.setBounds(0, 0, rightPanel.getWidth()-3, 25);
         sp.setSize((int)JSplitPane1.getLeftComponent().getBounds().getWidth()-2,(int)JSplitPane1.getLeftComponent().getBounds().getHeight()-2 );
         sp.repaint();
              bottomPanel.setBounds(0,26,rightPanel.getWidth()-3,rightPanel.getHeight()-28);
    }

    hi sculz,
    i develped the tree, and tree selection listener also the 4 th point i didnt able to do . here is the code belo what i did.
    iam not able to add the JSplit pane also.
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class Tree08 extends JFrame{
    Hashtable theHashtable = new Hashtable();
    int frameWidth = 300;
    int frameHeight = 305;
    int numberRows = 19;
    JTree tree;
    JPanel treePanel;
    String plafClassName =
    "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
    For future reference, the three plaf implementations
    are:
    com.sun.java.swing.plaf.metal.MetalLookAndFeel
    com.sun.java.swing.plaf.motif.MotifLookAndFeel
    com.sun.java.swing.plaf.windows.WindowsLookAndFeel
    JLabel display;
    public static void main(String args[]) {
    new Tree08();
    public Tree08 () {
    theHashtable.put("Cabbage","Good in slaw");
    theHashtable.put("Squash","The yellow variety");
    theHashtable.put("Onion","Not too hot");
    theHashtable.put("Squirrel","Likes to store nuts");
    theHashtable.put("Rabbit","Runs fast");
    theHashtable.put("Fox","Crazy like a ...");
    theHashtable.put("Horse","Fun to ride");
    theHashtable.put("Pig","Lives in mud");
    theHashtable.put("Cow","Gives us milk");
    theHashtable.put("Peach","From Georgia");
    theHashtable.put("Grape","Saueeze into wine");
    theHashtable.put("Apple","Red delicious");
    theHashtable.put("Orange","Very juicy");
    DefaultMutableTreeNode[] theTreeNodes = new
    DefaultMutableTreeNode[numberRows];
    theTreeNodes[0] = new DefaultMutableTreeNode("Sample
    Tree");
    theTreeNodes[1] = new
    DefaultMutableTreeNode("Vegetables");
    theTreeNodes[2] = new
    DefaultMutableTreeNode("Cabbage");
    theTreeNodes[3] = new
    DefaultMutableTreeNode("Squash");
    theTreeNodes[4] = new
    DefaultMutableTreeNode("Onion");
    theTreeNodes[5] = new
    DefaultMutableTreeNode("Animals");
    theTreeNodes[6] = new
    DefaultMutableTreeNode("Forrest");
    theTreeNodes[7] = new
    DefaultMutableTreeNode("Squirrel");
    theTreeNodes[8] = new
    DefaultMutableTreeNode("Rabbit");
    theTreeNodes[9] = new DefaultMutableTreeNode("Fox");
    theTreeNodes[10] = new
    DefaultMutableTreeNode("Farm");
    theTreeNodes[11] = new
    DefaultMutableTreeNode("Horse");
    theTreeNodes[12] = new DefaultMutableTreeNode("Pig");
    theTreeNodes[13] = new DefaultMutableTreeNode("Cow");
    theTreeNodes[14] = new
    DefaultMutableTreeNode("Fruit");
    theTreeNodes[15] = new
    DefaultMutableTreeNode("Peach");
    theTreeNodes[16] = new
    DefaultMutableTreeNode("Grape");
    theTreeNodes[17] = new
    DefaultMutableTreeNode("Apple");
    theTreeNodes[18] = new
    DefaultMutableTreeNode("Orange");
    theTreeNodes[0].add(theTreeNodes[1]);
    theTreeNodes[1].add(theTreeNodes[2]);
    theTreeNodes[1].add(theTreeNodes[3]);
    theTreeNodes[1].add(theTreeNodes[4]);
    theTreeNodes[0].add(theTreeNodes[5]);
    theTreeNodes[5].add(theTreeNodes[6]);
    theTreeNodes[6].add(theTreeNodes[7]);
    theTreeNodes[6].add(theTreeNodes[8]);
    theTreeNodes[6].add(theTreeNodes[9]);
    theTreeNodes[5].add(theTreeNodes[10]);
    theTreeNodes[10].add(theTreeNodes[11]);
    theTreeNodes[10].add(theTreeNodes[12]);
    theTreeNodes[10].add(theTreeNodes[13]);
    theTreeNodes[0].add(theTreeNodes[14]);
    theTreeNodes[14].add(theTreeNodes[15]);
    theTreeNodes[14].add(theTreeNodes[16]);
    theTreeNodes[14].add(theTreeNodes[17]);
    theTreeNodes[14].add(theTreeNodes[18]);
    treePanel = new TreePanel(theTreeNodes[0]);
    tree.addTreeSelectionListener(new MyTreeListener());
    Container content = getContentPane();
    content.add(treePanel,BorderLayout.CENTER);
    display = new JLabel("Display Selection Here");
    content.add(display,BorderLayout.SOUTH);
    setSize(frameWidth, frameHeight);
    setTitle("Copyright 1998, R.G.Baldwin");
    setVisible(true);
    this.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);}
    class MyTreeListener implements TreeSelectionListener{
    public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode theNode =
    (DefaultMutableTreeNode)
    (e.getPath().getLastPathComponent());
    if (theNode.isLeaf()) {
    display.setText((String)theHashtable.get(
    theNode.getUserObject()));
    class TreePanel extends JPanel {
    public TreePanel(TreeNode root){
    setLayout(new BorderLayout());
    tree = new JTree(root);
    JScrollPane sp = new JScrollPane(tree);
    add(sp, BorderLayout.CENTER);
    try{
    UIManager.setLookAndFeel(plafClassName);
    }catch(Exception ex){System.out.println(ex);}
    SwingUtilities.updateComponentTreeUI(this);
    for(int cnt = 0; cnt < numberRows; cnt++){
    tree.expandRow(cnt);
    regards
    sonali

  • How to disable selection of root node in JTree

    Hi all! Thanks for taking a minute to read my post!
    I am writing a really basic JTree for showing a list of items.
    Here is some of the code:
    /** Create a basic tree **/
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Title");
    DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    JTree tree = new JTree(treeModel);
    /** Method to return the string of the current highlighted selection **/
    public String getSelectionString()
    DefaultMutableTreeNode node =
    tree.getSelectionPath().getLastPathComponent();
    return (String)node.getUserObject();
    I would like to disable selection of the root node of my JTree.
    Thus, if I make a call to getSelectionString() above, it would return null instead of the string that represents the root label.
    I have read the following forum on disabling various TreePaths and TreeNodes in a JTree:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=224691
    This forum suggests implementing the TreeSelectionListener interface and the TreeSelectionModel class and over-riding the addSelectedPath() methods. I tried this suggestion, and I was able to enable and disable the different children of the Jtree, but the root of the JTree would not disable.
    I suppose that I could just simply remove the visibility of the root node, but I really want to avoid that option if possible.
    Wait --- let me be clear ---- I want to disable the selection of the root node only - still allowing selection of all its children.
    Any suggestions?
    Am I missing something really simple here?
    Did I explain my problem clearly?
    Thanks in advance!
    jewels

    simply try this..
    in the
    public void valueChanged(javax.swing.event.TreeSelectionEvent event);
    method of TreeSelectionListener impelentation get the
    TreePath tp = event.getPath();
    from TreePath get the component and then remove the selection from the treePath if it is the node u were checking/root node in this case
    tree.getSelectionModel().removeSelectionPath(tp);
    Try out....

  • Problem with new window opening with basic test JTree program

    I'm still getting to grips with Swing, and have now moved on to basic JTrees.
    I'm currently trying to use an add and delete button to add new nodes to the root etc. The addition and deletion is working ok, except that each time the addButton is pressed, a completely new window is created on top of the current window with the new node added to the root etc.
    I know this is probably a simple mistake, but I can't quite see it at the moment.
    My current code is as follows,
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public class TreeAdditionDeletionTester_1 extends JFrame implements ActionListener
        private JTree tree;
        private DefaultTreeModel treeModel;
        private DefaultMutableTreeNode rootNode;
        private JButton addButton;
        private JButton deleteButton;
        private JPanel panel;
        private int newNodeSuffix = 1;
        private static String Add_Command = "Add Node";
        private static String Delete_Command = "Remove Node";
        //DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
        //TreeAdditionDeletionTester_1 treeChange;
        public TreeAdditionDeletionTester_1() 
            setTitle("Tree with Add and Remove Buttons");
            //DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
            rootNode = new DefaultMutableTreeNode("Root");
            treeModel = new DefaultTreeModel(rootNode);
            tree = new JTree(treeModel);
            tree.setEditable(false);
            tree.setSelectionRow(0);
            JScrollPane scrollPane = new JScrollPane(tree);
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            JPanel panel = new JPanel();
            addButton = new JButton("Add Node");
            addButton.setActionCommand(Add_Command);
            addButton.addActionListener(this);
            panel.add(addButton);
            getContentPane().add(panel, BorderLayout.SOUTH);
            deleteButton = new JButton("Delete Node");
            deleteButton.setActionCommand(Delete_Command);
            deleteButton.addActionListener(this);
            panel.add(deleteButton);
            getContentPane().add(panel, BorderLayout.SOUTH);    
            setSize(300, 400);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setVisible(true);
        public void actionPerformed(ActionEvent event) 
           TreeAdditionDeletionTester_1 treeChange = new TreeAdditionDeletionTester_1();
            String command = event.getActionCommand();
            if (Add_Command.equals(command)) {
                //Add button clicked
                treeChange.addObject("New Node " + newNodeSuffix++);
            } if (Delete_Command.equals(command)) {
                //Remove button clicked
                treeChange.removeCurrentNode();
        public void removeSelectedNode()
            //get the selected node
            DefaultMutableTreeNode selNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            //method from Class JTree
            if (selNode != null)
                //get the parent of the selected node
                MutableTreeNode parent = (MutableTreeNode)(selNode.getParent());
                //getParent() from Interface TreeNode
                // if the parent is not null
                if (parent != null)
                    //remove the node from the parent
                    treeModel.removeNodeFromParent(selNode);//method from Class DefaultTreeModel
                    return;
        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,
                                                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 new node.
            if (shouldBeVisible) {
                tree.scrollPathToVisible(new TreePath(childNode.getPath()));
            return childNode;
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child) {
            return addObject(parent, child, false);
        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;
         * Main method to run as an Application
        public static void main(String[] arg) 
            TreeAdditionDeletionTester_1 addDeleteTree = new TreeAdditionDeletionTester_1();
    }      Thanks.

    I'm currently trying to use an add and delete button
    to add new nodes to the root etc. The addition and
    deletion is working ok, except that each time the
    addButton is pressed, a completely new window is
    created on top of the current window with the new
    node added to the root etc.
    I know this is probably a simple mistake, but I can't
    quite see it at the moment.
    Look at the actionPerformed code for your buttons. The first thing you do there is to create a new TreeAdditionDeletionTester_1, so I don't know why you are surprised you get a new window. There is no need to create a new instance in there, just call addObject/removeCurrentNode on the "this" instance.

  • JTree not updating

    i've already make changes to the nodes in a jtree, then i try using
    jtree.repaint();, jtree.validate();, all didn't update the display..
    why is it like that?
    i try using jtree.updateUI(), it works but got some problem when calling from other class(can't understand the reason) it give this error:
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTreeUI.paintRow(BasicTreeUI.java:1309)
         at javax.swing.plaf.basic.BasicTreeUI.paint(BasicTreeUI.java:1120)
         at javax.swing.plaf.metal.MetalTreeUI.paint(MetalTreeUI.java:139)
         at javax.swing.plaf.ComponentUI.update(ComponentUI.java:39)
         at javax.swing.JComponent.paintComponent(JComponent.java:395)
         at javax.swing.JComponent.paint(JComponent.java:687)
         at javax.swing.JComponent.paintWithBuffer(JComponent.java:3878)
         at javax.swing.JComponent._paintImmediately(JComponent.java:3821)
         at javax.swing.JComponent.paintImmediately(JComponent.java:3672)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:370)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:124)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:154)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:337)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)

    I suppose you are adding/removing nodes of the tree using a TreeModel or TreeNode
    So then calling updateUI may not be good enough
    You should be firing the events fireTreeNodesRemoved/fireTreeNodesInserted
    You can do the same using the methods nodesWereRemoved/nodesWereInserted
    of TreeModel
    Incase you are just changing some properties of the node , You may use nodesChanged

  • Somebody help me on JTree

    Dear Everyone,
    I got a big problem now, need you give me a hand.
    I have to use the JFileChooser to load a package which contains lots of .class file, then shows the whole file by JTree as well.How can I do that? I have tried for a whole day, but failed.
    Help me, thanks a million.

    Here's something I've coded once. Please inspect it before using it.
    I have used it once and it worked. But you never know...
    import java.io.File;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Enumeration;
    import javax.swing.tree.TreeNode;
    public
    class FileTreeNode
    implements TreeNode
      protected
      File file;
      public
      FileTreeNode(String fileName)
        this(new File(fileName));
      public
      FileTreeNode(File file)
        this.file = file;
      public
      Enumeration children()
        return
          Collections.enumeration(Arrays.asList(file.listFiles()));
    public
      boolean getAllowsChildren()
        return
          file.isDirectory();
      public
      TreeNode getChildAt(int index)
        return
          new FileTreeNode(file.listFiles()[index].toString());
      public
      int getChildCount()
        return
          file.listFiles().length;
      public
      int getIndex(TreeNode node)
        if (node instanceof FileTreeNode)
          return
          Arrays.asList(file.listFiles()).indexOf(node);
        else
          return
            -1;
      public
      TreeNode getParent()
        return
          file.getParentFile()!=null? new FileTreeNode(file.getParentFile()) : null;
      public
      boolean isLeaf()
        return
          !file.isDirectory();
      public
      int hashCode()
        return file.hashCode();
      public
      boolean equals(Object object)
        return
          object instanceof FileTreeNode
          && file.equals(((FileTreeNode)object).file);
      public
      String toString()
        return file!=null
          ? file.getName()
    }import java.util.Iterator;
    import java.util.Arrays;
    import javax.swing.event.EventListenerList;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreeNode;
    import javax.swing.tree.TreePath;
    public
    class MinimalTreeModel
    implements TreeModel
    protected
    TreeNode root;
    protected
    EventListenerList listeners;
    public
    MinimalTreeModel(TreeNode root)
    this.root = root;
    listeners = new EventListenerList();
    public
    void removeTreeModelListener(TreeModelListener l)
    listeners.remove(TreeModelListener.class, l);
    public
    void addTreeModelListener(TreeModelListener l)
    listeners.add(TreeModelListener.class, l);
    public
    Object getRoot()
    return
    root;
    public
    boolean isLeaf(Object node)
    return
    node instanceof TreeNode
    && ((TreeNode)node).isLeaf();
    public
    int getIndexOfChild(Object parent, Object child)
    return
    parent instanceof TreeNode && child instanceof TreeNode
    ? ((TreeNode)parent).getIndex((TreeNode)child)
    : -1;
    public
    Object getChild(final Object parent, final int index)
    return
    parent instanceof TreeNode
    ? ((TreeNode)parent).getChildAt(index)
    : null;
    public
    int getChildCount(Object parent)
    return
    parent instanceof TreeNode
    ? ((TreeNode)parent).getChildCount()
    : 0;
    public
    void valueForPathChanged(TreePath path, Object value)
    Iterator i;
    TreeModelEvent e;
    i = Arrays.asList(listeners.getListeners(TreeModelListener.class)).iterator();
    e = new TreeModelEvent(this, path);
    while (i.hasNext())
    ((TreeModelListener)i.next()).treeNodesChanged(e);

  • How can Display a specified sub set of a Jtree??

    Dear Friends: Good weekends:
    I have following code:
    import javax.swing.*;
    import javax.swing.tree.*;
    import apl.jhu.edu.JTree.ExitListener;
    import apl.jhu.edu.JTree.WindowUtilities;
    import java.awt.*;
         public class JTreeCars  extends JFrame {
           DefaultTreeModel treeModel;
           public JTreeCars() {
             super("Editable Tree Frame");
                JTreeSub js = new JTreeSub();
             setSize(200, 200);
             WindowUtilities.setNativeLookAndFeel();
             addWindowListener(new ExitListener());
             setDefaultCloseOperation(EXIT_ON_CLOSE);
           public class JTreeSub  extends JTree {
                public JTreeSub() {
                super();
                init();
           public void init(){
             DefaultMutableTreeNode Manufacturers = new DefaultMutableTreeNode("Car Makers");
             DefaultMutableTreeNode Cars = new DefaultMutableTreeNode("Cars");
             DefaultMutableTreeNode Nissan = new DefaultMutableTreeNode("Nissan");
             DefaultMutableTreeNode Nissan90 = new DefaultMutableTreeNode("Nissan90");
             DefaultMutableTreeNode Nissan91 = new DefaultMutableTreeNode("Nissan91");
             DefaultMutableTreeNode Nissan92 = new DefaultMutableTreeNode("Nissan92");
             DefaultMutableTreeNode Nissan95 = new DefaultMutableTreeNode("Nissan95");
             DefaultMutableTreeNode Nissan98 = new DefaultMutableTreeNode("Nissan98");
             DefaultMutableTreeNode Nissan2001 = new DefaultMutableTreeNode("Nissan2001");
             DefaultMutableTreeNode Nissan2002 = new DefaultMutableTreeNode("Nissan2002");
             DefaultMutableTreeNode Nissan2003 = new DefaultMutableTreeNode("Nissan2003");
             DefaultMutableTreeNode Nissan99 = new DefaultMutableTreeNode("Nissan99");
                  Nissan.add(Nissan90);
                  Nissan.add(Nissan91);
                  Nissan.add(Nissan92);
                  Nissan.add(Nissan95);
                  Nissan.add(Nissan98);
                  Nissan.add(Nissan99);
                  Nissan.add(Nissan2001);
                  Nissan.add(Nissan2002);
                  Nissan.add(Nissan2003);
             DefaultMutableTreeNode Ford = new DefaultMutableTreeNode("Ford");
             DefaultMutableTreeNode Ford2001 = new DefaultMutableTreeNode("Ford2001");
             DefaultMutableTreeNode Ford2002 = new DefaultMutableTreeNode("Ford2002");
             DefaultMutableTreeNode Ford2003 = new DefaultMutableTreeNode("Ford2003");
             DefaultMutableTreeNode Ford2004 = new DefaultMutableTreeNode("Ford2004");
             DefaultMutableTreeNode Ford2005 = new DefaultMutableTreeNode("Ford2005");
                  Ford.add(Ford2001);
                  Ford.add(Ford2002);
                  Ford.add(Ford2003);
                  Ford.add(Ford2004);
                  Ford.add(Ford2005);
             DefaultMutableTreeNode Benz = new DefaultMutableTreeNode("Benz");
             DefaultMutableTreeNode Benz81 = new DefaultMutableTreeNode("Benz81");
             DefaultMutableTreeNode Benz82 = new DefaultMutableTreeNode("Benz82");
             DefaultMutableTreeNode Benz83 = new DefaultMutableTreeNode("Benz83");
             DefaultMutableTreeNode Benz84 = new DefaultMutableTreeNode("Benz84");
             DefaultMutableTreeNode Benz85 = new DefaultMutableTreeNode("Benz85");
             DefaultMutableTreeNode Benz2001 = new DefaultMutableTreeNode("Benz2001");
             DefaultMutableTreeNode Benz2002 = new DefaultMutableTreeNode("Benz2002");
             DefaultMutableTreeNode Benz2003 = new DefaultMutableTreeNode("Benz2003");
                  Benz.add(Benz81);
                  Benz.add(Benz82);
                  Benz.add(Benz83);
                  Benz.add(Benz84);
                  Benz.add(Benz85);
                  Benz.add(Benz2001);
                  Benz.add(Benz2002);
                  Benz.add(Benz2003);
             DefaultMutableTreeNode Toyota = new DefaultMutableTreeNode("Toyota");
             DefaultMutableTreeNode Cherry = new DefaultMutableTreeNode("Cherry");
             treeModel = new DefaultTreeModel(Manufacturers);
             JTree tree = new JTree(treeModel);
             tree.setEditable(true);
             treeModel.insertNodeInto(Cars,Manufacturers, 0);
             Cars.add(Nissan);
             Cars.add(Ford);
             Cars.add(Benz);
             Cars.add(Toyota);
             Cars.add(Cherry);
             getContentPane().add(tree, BorderLayout.CENTER);
           public static void main(String args[]) {
                JTreeCars st = new JTreeCars();
                st.setVisible(true);
         }I only hope to display subset of this whole JTree, ie, the Nodes with 2001, 2002, 2003 will be displayed, all others will be hidden, not to display
    Here I hope only the node contains "2001" , "2002", "2003" will be displayed. all others will not be displayed.
    Please advice how to do it??
    Thanks a nd have a good weekends.
    sunny

    Thanks Michael,
    I just post my updated code, I hope if I uncheck the box, all tree will be displayed, if I check it, Only 2001,2002, 2003 cars show up, looks like my code not work, what is wrong here??
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeNode;
    class FilterTreeModel extends DefaultTreeModel {
           Filter filter;
           String sText;
           public FilterTreeModel(TreeNode root, Filter filter) {
             super(root);
             this.filter =filter;
           public void setFiltered(boolean pass, String sstr) {
             filter.setFiltered(pass,sstr );
             sText=sstr;
             Object[] path = {root};
             int[] childIndices  = new int[root.getChildCount()];     
             Object[] children  = new Object[root.getChildCount()];
             for (int i = 0; i < root.getChildCount(); i++) {
               childIndices[i] = i;
               children[i] = root.getChildAt(i);
             fireTreeStructureChanged(this,path,childIndices, children);
           public int getChildCount(Object parent) {
             int realCount = super.getChildCount(parent), filterCount=0;
             for (int i=0; i<realCount; i++) {
               DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)super.getChild(parent,i);
               if (filter.pass(dmtn, sText)) filterCount++;
             return filterCount;
           public Object getChild(Object parent, int index) {
             int cnt=-1;
             for (int i=0; i<super.getChildCount(parent); i++) {
               Object child = super.getChild(parent,i);
               if (filter.pass(child,sText)) cnt++;
               if (cnt==index) return child;
             return null;
         interface Filter {
           public boolean pass(Object obj, String stt);
           public void setFiltered(boolean pass, String str);
           public boolean isFiltered();
         class MyFilter implements Filter {
           boolean pass=true;
           String  strFilter;
           public boolean pass(Object obj, String sttr) {
             if (pass) return true;
             //char c = obj.toString().charAt(0);
             String c = obj.toString();
            // return Character.toLowerCase(c)<0;
             return c.contains(sttr);
           public void setFiltered(boolean pass, String str) {
                this.pass=pass;
                strFilter= str;
           public boolean isFiltered() {
                return pass;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class JTreeCarDemo extends JFrame {
      JTreeSub jt = new JTreeSub();
      MyFilter mf = new MyFilter();
      JCheckBox jcb = new JCheckBox("Filter");
      FilterTreeModel ftm = new FilterTreeModel((TreeNode)jt.getModel().getRoot(), mf);
      DefaultTreeModel treeModel;
      public JTreeCarDemo() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        jt.setModel(ftm);
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        content.add(jcb, BorderLayout.SOUTH);
        jcb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            ftm.setFiltered(!jcb.isSelected(), "200");
        setSize(500, 700);
        setVisible(true);
        setTitle("New Car from 2000");
      public static void main(String[] args) {
           new JTreeCarDemo();
      public class JTreeSub  extends JTree {
           public JTreeSub() {
           super();
             DefaultMutableTreeNode Manufacturers = new DefaultMutableTreeNode("Car Makers");
             DefaultMutableTreeNode Cars = new DefaultMutableTreeNode("Cars");
             DefaultMutableTreeNode Nissan = new DefaultMutableTreeNode("Nissan");
             DefaultMutableTreeNode Nissan90 = new DefaultMutableTreeNode("Nissan90");
             DefaultMutableTreeNode Nissan91 = new DefaultMutableTreeNode("Nissan91");
             DefaultMutableTreeNode Nissan92 = new DefaultMutableTreeNode("Nissan92");
             DefaultMutableTreeNode Nissan95 = new DefaultMutableTreeNode("Nissan95");
             DefaultMutableTreeNode Nissan98 = new DefaultMutableTreeNode("Nissan98");
             DefaultMutableTreeNode Nissan2001 = new DefaultMutableTreeNode("Nissan2001");
             DefaultMutableTreeNode Nissan2002 = new DefaultMutableTreeNode("Nissan2002");
             DefaultMutableTreeNode Nissan2003 = new DefaultMutableTreeNode("Nissan2003");
             DefaultMutableTreeNode Nissan99 = new DefaultMutableTreeNode("Nissan99");
             Nissan.add(Nissan90);
             Nissan.add(Nissan91);
             Nissan.add(Nissan92);
             Nissan.add(Nissan95);
             Nissan.add(Nissan98);
             Nissan.add(Nissan99);
             Nissan.add(Nissan2001);
             Nissan.add(Nissan2002);
             Nissan.add(Nissan2003);
        DefaultMutableTreeNode Ford = new DefaultMutableTreeNode("Ford");
        DefaultMutableTreeNode Ford2001 = new DefaultMutableTreeNode("Ford2001");
        DefaultMutableTreeNode Ford2002 = new DefaultMutableTreeNode("Ford2002");
        DefaultMutableTreeNode Ford2003 = new DefaultMutableTreeNode("Ford2003");
        DefaultMutableTreeNode Ford2004 = new DefaultMutableTreeNode("Ford2004");
        DefaultMutableTreeNode Ford2005 = new DefaultMutableTreeNode("Ford2005");
             Ford.add(Ford2001);
             Ford.add(Ford2002);
             Ford.add(Ford2003);
             Ford.add(Ford2004);
             Ford.add(Ford2005);
        DefaultMutableTreeNode Benz = new DefaultMutableTreeNode("Benz");
        DefaultMutableTreeNode Benz81 = new DefaultMutableTreeNode("Benz81");
        DefaultMutableTreeNode Benz82 = new DefaultMutableTreeNode("Benz82");
        DefaultMutableTreeNode Benz83 = new DefaultMutableTreeNode("Benz83");
        DefaultMutableTreeNode Benz84 = new DefaultMutableTreeNode("Benz84");
        DefaultMutableTreeNode Benz85 = new DefaultMutableTreeNode("Benz85");
        DefaultMutableTreeNode Benz2001 = new DefaultMutableTreeNode("Benz2001");
        DefaultMutableTreeNode Benz2002 = new DefaultMutableTreeNode("Benz2002");
        DefaultMutableTreeNode Benz2003 = new DefaultMutableTreeNode("Benz2003");
             Benz.add(Benz81);
             Benz.add(Benz82);
             Benz.add(Benz83);
             Benz.add(Benz84);
             Benz.add(Benz85);
             Benz.add(Benz2001);
             Benz.add(Benz2002);
             Benz.add(Benz2003);
        DefaultMutableTreeNode Toyota = new DefaultMutableTreeNode("Toyota");
        DefaultMutableTreeNode Cherry = new DefaultMutableTreeNode("Cherry");
        treeModel = new DefaultTreeModel(Manufacturers);
        JTree tree = new JTree(treeModel);
        tree.setEditable(true);
        //treeModel.insertNodeInto(Cars,Manufacturers, 0);
        Manufacturers.add(Cars);
        Cars.add(Nissan);
        Cars.add(Ford);
        Cars.add(Benz);
        Cars.add(Toyota);
        Cars.add(Cherry);
        getContentPane().add(tree, BorderLayout.CENTER);
    }

  • Selecting a node in a JTree knowing his path

    Hello for all,
    I'm trying to select a specific node in a JTree component by clicking a button.. this is my code :
    private DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode("root");
    private DefaultTreeModel treeModel = new DefaultTreeModel(treeNode);
    private JTree tree = new JTree(treeModel);
    private JButton button = new JButton("Select");
    DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("child1");
    DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("child2");
    child1.add(new DefaultMutableTreeNode("child11"));
    treeNode.add(child1);
    treeNode.add(child2);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        TreePath path = new TreePath(new Object[]{"root", "child1"});               
        tree.setExpandsSelectedPaths(true);
        tree.scrollPathToVisible(path);
    });as you can see, I want to select the node with the path "root/child1"..
    but I'm getting this exception : Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.tree.TreeNode..
    any ideas ?

    You will want to read the second sentence in the TreePath comments section.
    Also, read the second sentence in the TreePath Method Detail section for the
    getLastPathComponent method.
    With these clues &#8212; try getting a TreePath from the tree you are working with.
    For example, you can try something like tree.getPathForRow(row) using the
    visible row index of "child1". Since the TreePath returned comes from the tree
    it will understand what to do with it. You can check the class name of the
    components that are returned in the TreePath to confirm this. And it will
    explain the exception you quoted.

Maybe you are looking for