JTree Help

Hi,
I'm having trouble trying to override the tree icons when the tree is
either expanded or collapsed. I used the following statements:
JTree tree = new JTree();
ImageIcon plusIcon = new ImageIcon( "./plus.gif" );
ImageIcon minusIcon = new ImageIcon( "./minus.gif" );
BasicTreeUI treeUI = ( BasicTreeUI )tree.getUI();
treeUI.setCollapsedIcon( plusIcon );
treeUI.setExpandedIcon( minusIcon );I was able to override the default icons, but
the problem I'm having is that my tree no longer
expanded or collapsed when I click on the new
icon. Instead, I have to click on the node Icon to
get it to expand or collapse. Please help.
Thank you in advance,

Try the following
UIManager.put("Tree.expandedIcon", plusIcon);
UIManager.put("Tree.collapsedIcon", minusIcon);
tree.updateUI();

Similar Messages

  • TreePath//JTree help

    I posted this yesturday and I thought I had it working, but I guess it isn't. So once more if somebody can help that is great.
    I am using a FileTree Class (extending JTree) to represent the file structure on my computer. What I am trying to do is the following:
    1) take a File Object and turn it into a valid TreePath for the FileTree I have already created.
    2) use the JTree.scrollPathToVisible(TreePath) command to expand all folders and put the File Object in the viewable portion of the tree.
    This is to essentially remember and start where the user last was browsing.
    I think my problem is with my procedure converting the File Object into a valid TreePath. My createPath procedure:
      //returns treepath for a specified file
      public TreePath createPath(File f) {
        List paths = new ArrayList();
        try {
          paths.add(new FileTreeNode(f, f.toString()));
        } catch (FileNotFoundException e) {
          System.out.println("FileNotFoundException (5): " + e);
        System.out.println(f.toString());
        while((f = f.getParentFile()) != null) {
          System.out.println(f.toString());
          try {
            paths.add(new FileTreeNode(f, f.toString()));
          } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException (4): " + e);
        return new TreePath(paths.toArray());
      }Where FileTreeNode is the TreeNode used by my FileTree class.
    The output I get:
    C:\scott\z4
    C:\scott
    FileNotFoundException (4): java.io.FileNotFoundException: File C:\scott does not exist
    C:\
    FileNotFoundException (4): java.io.FileNotFoundException: File C:\ does not existAny help is appreciated.

    up once

  • Filtering JTree help

    Hello,
    I have a situation where 10,000+ records are organized in a JTree. To make it easier on my users, I would like to allow them to filter the records through a text field. SInce there are so many records, I do not want to filter the whole set. Instead, I would like to filter the children of the currently selected node. if no node is selected, filter only the "top" (level below hidden root).
    I searched the forums on how to filter JTrees, and I thought I had pieced together a working filter model. Once I tried it, I ran into the following error:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Null chil
    d not allowed
    at javax.swing.tree.TreePath.pathByAddingChild(Unknown Source)
    at javax.swing.tree.VariableHeightLayoutCache$TreeStateNode.setParent(Un
    known Source)
    at javax.swing.tree.DefaultMutableTreeNode.insert(Unknown Source)
    at javax.swing.tree.DefaultMutableTreeNode.add(Unknown Source)
    at javax.swing.tree.VariableHeightLayoutCache$TreeStateNode.expand(Unkno
    wn Source)
    at javax.swing.tree.VariableHeightLayoutCache$TreeStateNode.expand(Unkno
    wn Source)
    at javax.swing.tree.VariableHeightLayoutCache.ensurePathIsExpanded(Unkno
    wn Source)
    at javax.swing.tree.VariableHeightLayoutCache.setExpandedState(Unknown S
    ource)
    at javax.swing.plaf.basic.BasicTreeUI.updateExpandedDescendants(Unknown
    Source)
    at javax.swing.plaf.basic.BasicTreeUI$Handler.treeExpanded(Unknown Sourc
    e)
    at javax.swing.JTree.fireTreeExpanded(Unknown Source)
    at javax.swing.JTree.setExpandedState(Unknown Source)
    at javax.swing.JTree.expandPath(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.toggleExpandState(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.selectPathForEvent(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI$Handler.handleSelectionImpl(Unknow
    n Source)
    at javax.swing.plaf.basic.BasicTreeUI$Handler.handleSelection(Unknown So
    urce)
    at javax.swing.plaf.basic.BasicTreeUI$Handler.mousePressed(Unknown Sourc
    e)
    at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
    at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    This occurs when I am expanding the filtered JTree, usually about 2 or 3 levels in (not counting hidden root).
    Below is my filter JTree Model class:
    public class FilteredJTreeModel extends DefaultTreeModel{
        String filterString=null;
         private DefaultTreeModel delegate;
         private TreeNode selectedNode=null;
        /** Creates a new instance of FilteredJTreeModel */
         public FilteredJTreeModel(DefaultTreeModel delegate){
             super((TreeNode) delegate.getRoot());
             this.delegate=delegate;
        public void refilter(String fylter, TreeNode levelNode){
            filterString=fylter;
            selectedNode=levelNode;
            setFilter(true, levelNode);
        public void setFilter(boolean pass, TreeNode aNode){
            final TreeNode root=aNode;
            final int childCount = root.getChildCount();
            final int[] indices = new int[childCount];
            final Object[] children = new Object[childCount];
            for(int i=0; i<childCount; i++){
                indices=i;
    children[i] = getChild(root, i);
    fireTreeStructureChanged(this, new Object[]{root}, indices, children);
    public int getChildCount(Object parent){
    int count=0;
    for(int i=0; i<delegate.getChildCount(parent); i++){
    final Object child=delegate.getChild(parent, i);
    if(isShown(child)){
    count++;
    }else{
    return count;
    public Object getChild(Object parent, int index){
    int count=0;
    for(int i=0; i< delegate.getChildCount(parent); i++){
    final Object child=delegate.getChild(parent, i);
    if(isShown(child)){
    if(count++ == index){
    return child;
    }else{
    return null;
    return null;
    public int getIndexOfChild(Object parent, Object child){
    return delegate.getIndexOfChild(parent, child);
    public boolean isLeaf(Object node){
    if(isShown(node)){
    return delegate.isLeaf(node);
    return false;
    private boolean isShown(Object node){
    final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node;
    final String objStr = treeNode.getUserObject().toString();
    if(filterString==null || filterString=="")return true;
    if(selectedNode!=null && !treeNode.isRoot()){
    TreeNode[] array=((DefaultMutableTreeNode)selectedNode).getPath();
    for(int x=0; x<array.length; x++){
    if(((DefaultMutableTreeNode)array[x]).equals(treeNode)){
    return true;
    return (objStr.indexOf(filterString, 0)!=-1);
    The code for my JTree class is:
    public class JpenoTree extends JTree{
        private FilterField filterField;
        private int DEFAULT_WIDTH=20;
        /** Creates a new instance of JpenoTree */
        public JpenoTree() {
            super();
            filterField = new FilterField(20);
            setModel(new FilteredJTreeModel((DefaultTreeModel)getModel()));
            this.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent e) {
                    treeValueChanged(e);
        public JpenoTree(TreeNode root){
            super(root);
            filterField = new FilterField(20);
            setModel(new FilteredJTreeModel((DefaultTreeModel)getModel()));
            this.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent e) {
                    treeValueChanged(e);
       public JpenoTree.FilterField getFilterField() {
            return filterField;
        public void treeValueChanged(TreeSelectionEvent e) {
            System.err.println("Selected Node: "+((DefaultMutableTreeNode)e.getPath().getLastPathComponent()).getUserObject().toString());
            filterField.setSelectedNode((TreeNode)e.getPath().getLastPathComponent());
        class FilterField extends JTextField implements DocumentListener{
            private TreeNode selectedNode;
            public FilterField(int width){
                super(width);
                getDocument().addDocumentListener(this);
            public void changedUpdate(DocumentEvent e){
                ((FilteredJTreeModel)getModel()).refilter(this.getText(),
                        (TreeNode)((selectedNode==null)?getModel().getRoot():selectedNode));
            public void insertUpdate(DocumentEvent e){
                ((FilteredJTreeModel)getModel()).refilter(this.getText(),
                        (TreeNode)((selectedNode==null)?getModel().getRoot():selectedNode));
            public void removeUpdate(DocumentEvent e){
                ((FilteredJTreeModel)getModel()).refilter(this.getText(),
                        (TreeNode)((selectedNode==null)?getModel().getRoot(): selectedNode));
            public void setSelectedNode(TreeNode selectedNode) {
                this.selectedNode = selectedNode;
            public TreeNode getSelectedNode() {
                return selectedNode;
    }Help is appreciated. Please bear in mind that I am new to Swing's M-V-C approach.
    Aaron

    I have something like this, and it works fine. Hope it helps.
        public Object getChild(Object parent, int index) {
            int realchildren = ((TreeNode) parent).getChildCount();
            if (filter == null) {
                return ((TreeNode) parent).getChildAt(index);
            if (realchildren == 0) {
                throw new ArrayIndexOutOfBoundsException("node has no children");
            int realIndex    = -1;
            int visibleIndex = -1;
            for (int i = 0; i < realchildren; i++) {
                TreeNodenode = (TreeNode) ((TreeNode) parent).getChildAt(i);
                if (filter.passNode(node)) {
                    visibleIndex++;
                realIndex++;
                if (visibleIndex == index) {
                    return ((TreeNode) parent).getChildAt(realIndex);
            throw new ArrayIndexOutOfBoundsException("index unmatched");
        public int getChildCount(Object parent) {
            int realchildren = ((TreeNode) parent).getChildCount();
            if (filter == null) {
                return realchildren;
            if (realchildren == 0) {
                return 0;
            int count = 0;
            for (int i = 0; i < realchildren; i++) {
                TreeNodenode = (TreeNode) ((TreeNode) parent).getChildAt(i);
                if (filter.passNode(node)) {
                    count++;
            return count;
        }

  • Please help me..JTRee expandPath().. thanks...please help!!!

    Hi all . THis is how I built my Jtree:'
    public class AECategory
    public String name;
    public String description;
    public String value;
    public AECategory(String name, String description, String value)
    this.name = name;
    this.description = description;
    this.value = value;
    public String toString() {return name;}
    public String getName() {    return name;}
    public String getDescription() {return description;}
    public String getValue() {    return value;}
    public void setName(String name) {this.name=name;}
    public void setDescription(String desc) {this.description=desc;}
    public void setValue(String val) {this.value=val;}
    public TreeModel buildCategoryTree(AECategory[] categories)
    System.out.println("Building a Tree Model now");
    System.out.println("Using "+categories.length+" categories");
    // Create an array of nodes
    DefaultMutableTreeNode[] nodes = new DefaultMutableTreeNode[categories.length];
    // Loop through all categories and create a node for every category
    for(int i=0;i<categories.length;i++)
    nodes[i] = new DefaultMutableTreeNode(categories); // Creates a node for this category
    System.out.println("nodes i :"+nodes[i]);
    // Now all nodes should be created, so we can start building the actual tree
    DefaultMutableTreeNode root = null;
    for(int i=0;i<categories.length;i++)
    String thisValue = categories[i].getValue(); // The current category value
    System.out.println("thisvalue :"+thisValue);
    String parentValue = ""; // The parents category value
    if(thisValue.indexOf('-')>0)
    parentValue = thisValue.substring(0, thisValue.lastIndexOf('-'));
    } else {
    root = nodes[i]; // We found the root element because there are no dashes in the value
    for(int loop=0;loop<categories.length;loop++)
    if(categories[loop].getValue().equals(parentValue))
    nodes[loop].add(nodes[i]); // Add this node to it's parent
    System.out.println("root:"+root);
    DefaultTreeModel treeModel = new DefaultTreeModel(root);
    return treeModel;
    and I have a JList, all I wanted is every time I double clicked at each item of the list, I want to following treepath to expand, but I didn't work for me.
    Here is my codes:
    lstOtherCategories.addListSelectionListener(new ListSelectionListener(){
    public void valueChanged(ListSelectionEvent le){
    if( (le.getValueIsAdjusting() == false) || (le.getFirstIndex()==-1) )
    return;
    Object[] path = new Object[2];
    DefaultMutableTreeNode alerts = new DefaultMutableTreeNode("Alerts");
    DefaultMutableTreeNode notes = new DefaultMutableTreeNode("Notes");
    path[0] = alerts; //replace myRootObject with your root object
    path[1] =notes;
    TreePath tp = new TreePath(path);
    System.out.println("tree path :" +tp);
    jtreeCategoryTree.expandPath(tp);
    }// end of public void valueChanged
    It compiled okey but It didn't do anything when I run..
    Please show me what I am doing wrong here. thanks a million

    Please help me!! does anyone knows about this.? please help

  • Help Needed in Building JTree

    HI,
    I've a doubt in Building a JTree.It wud be helpful if some one helps me with a better logic for building this Tree..
    I have a tree like this:
    root
    |
    A--B--C--D
    A--B--C--D
    A--B--C
    A--B--C--E--F
    I have the tree nodes like this . i need to merge the nodes like this
    root
    |
    A
    |
    -- B
    |
    --C
    |
    --D
    --E
    |
    --F
    I've tried it in few ways. It doesn't seems to be working.. Can some one help me in giving me a better logic in doing this

    Hello,
    When updating the tree, do not access the tree nodes directly. Update the tree via its (TreeModel).
    to get the model of your JTree use
    DefaultTreeModel treeModel = (DefaultTreeModel)myTree.getModel();to add nodes use the method
    treeModel.insertNodeInto(newChild,parent,offset);and remove nodes using
    treeModel.removeFromParent(nodeToRemove);--
    Regards,
    Ahmed Saad

  • 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

  • Help with JTree Update

    Hi there,
    I need to do a simple thing with a JTree but I 've got a problem. Well I want to create a very very very simple bookmark function. I have a tree with the children and I want to add new children which are going to work like link for my program. I try to add new children the same way I created them but it's not working. I tried also the updateUI method that somebody mentioned in an other topic but still nothing. Can somebody help?
    Here is the Bookmark Panel code:
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.awt.*;
    public class BookmarkTry implements TreeSelectionListener {
        private JScrollPane scrollPane;
        private JLabel label;
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Bookmarks");
        private JTree tree;
        private JPanel panel = new JPanel();
         public BookmarkTry(){
         public JPanel createpanel(){
         tree = new JTree(root);
         root.add(new DefaultMutableTreeNode(new Bookmark("Chapter 1","about.html")));
        root.add(new DefaultMutableTreeNode(new Bookmark("Chapter 2","aaa.html")));
        root.add(new DefaultMutableTreeNode(new Bookmark("Chapter 3","sdss.html")));
        // build tree
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree.addTreeSelectionListener(this);// get selection events!
        // build form
        scrollPane = new JScrollPane(tree);
        label = new JLabel(" ");
        //scrollPane.setViewportView(tree);
        panel.add(label);
        panel.add(scrollPane);
        return panel;
        public void addBookMarks(String name, String page){
             root.add(new DefaultMutableTreeNode(new Bookmark(name,page)));
             //DefaultTreeModel.reload();
        public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            if ((selectedNode!=null)&&(selectedNode.isLeaf())) {
                Bookmark b = (Bookmark)selectedNode.getUserObject();
                label.setText("Go to page "+b.getPage());
        private static class Bookmark {
            private String caption;
            private String page;
            public String getPage() {
                return page;
            public Bookmark(String caption, String page) {
                this.caption = caption;
                this.page = page;
            public String toString() {
                return caption;
         and here how I try to add the node :
    void jButton1_actionPerformed(ActionEvent e) throws java.sql.SQLException {
            DefaultMutableTreeNode book = null;
            System.out.println("You pressed the add button of bookmarkframe");
            //Bookmark.getTreePanel().addObject(name.getText());
            //book = new DefaultMutableTreeNode(new BookInfo(name.getText(),page.getText()));
            System.out.println(name.getText());
            System.out.println(page.getText());
            tempb.addBookMarks(name.getText(),page.getText());
            frame.dispose();
       } //void jButton1_actionPerformedIt doesn't add the new node in my JTree
    Thanks in advance

    I still suspect you have two (or more) new BookmarkTry() executions somewhere. But I can't see all of your code here of course. My standard reply, so we don't waste time guessing:
    1) In the future, Swing related questions should be posted in the Swing forum.
    2) If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
    Note, we don't want your whole application. We want an SSCCE!

  • Help with displaying a JTree

    Hi,
    I have developed a webspider that cycles through a website detecting all urls and checking for borken links. I currently have build a JTree that takes the current url that is being processed and creates a string and adds it to a JTree. The problem I have is that the urls are printed in the JTree as one long list, e.g.
    |Test
    |____url 1
    |____url 1a
    |____url 2
    |____url 2a
    I would like it to disply like this:
    |Test
    |____url 1
    |-------|____url 1a
    |____url 2
    |-------|____url 2a
    (I have had to place the dashes in so it displays properly)
    So that the strucutre of the website can be seen. I have read the JTree tutroial and my code looks like this, sorry its large i'm not too sure which bits to cut out:
    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 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);
                 clear.setText("Clear");
             clear.setActionCommand("Clear");
             toolBar.add(clear);
             ButtonListener clearListener = new ButtonListener();
                 clear.addActionListener(clearListener);
                 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 the scrol pane and text area to the error tab
             errorTab.add(errorPane);
             errorPane.setBounds(0,0,580,490);
             errorPane.getViewport().add(errorText);
             //add the scroll pane to the tree tab
             treeTab.add(treePane);
             treePane.setBounds(0,0,580,490);
             //create the JTree
             rootNode = new DefaultMutableTreeNode("Test");
             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);
             treePane.getViewport().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 clear = 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.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 == clear)
                            errorText.setText("");
                            rootNode.removeAllChildren();
                           treeModel.reload();
                       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";
                        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
                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 navigation errors found
              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;
                  //public String msgInfo = msg;
                     public void run()
                         current.setText("Currently Processing: " + msg );
                         addObject(msg);
             //add a node to the tree
                public DefaultMutableTreeNode addObject (Object child)
                 DefaultMutableTreeNode parentNode = null;
                 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());
                 if (shouldBeVisible)
                     tree.scrollPathToVisible(new TreePath(childNode.getPath()));
                      return childNode;
             //listener for the tree model     
             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)
    }It uses a class called webspider which i have not attached, if required please let me know. I beleive that in addObject I am adding all nodes to the root as children.
    Any help would be much appreciated.
    Many Thanks
    MRv

    I would recomend you create your own JTree class for this.
    Here are a few things I set in my constructor within the JTree:
    // turn on tooltips
    ToolTipManager.sharedInstance().registerComponent(this);
    // used by two setters so create reference
    RollupTreeCellRenderer renderer = new RollupTreeCellRenderer();
    // customizing the icons for the tree
    // setting the folder icons
    renderer.setOpenIcon(IconLoader.getIcon("Open.gif"));
    renderer.setClosedIcon(IconLoader.getIcon("Folder.gif"));
    // inventory icon
    renderer.setLeafIcon(IconLoader.getIcon("Document.gif"));
    // add renderer to highlight Inventory nodes with Red or Blue text
    setCellRenderer(renderer);
    Here is the renderer class example:
    class RollupTreeCellRenderer
    extends DefaultTreeCellRenderer
    * Configures the renderer based on the passed in components.
    * The value is set from messaging the tree with
    * <code>convertValueToText</code>, which ultimately invokes
    * <code>toString</code> on <code>value</code>.
    * The foreground color is set based on the selection and the icon
    * is set based on on leaf and expanded.
    * @param tree JTree
    * @param value Object
    * @param sel boolean
    * @param expanded boolean
    * @param leaf boolean
    * @param row int
    * @param hasFocus boolean
    * @return Component
    public Component getTreeCellRendererComponent(JTree tree, Object value,
    boolean sel,
    boolean expanded,
    boolean leaf, int row,
    boolean hasFocus)
    // call super for default behavior
    super.getTreeCellRendererComponent(tree,
    value,
    sel,
    expanded,
    leaf,
    row,
    hasFocus);
    // if the current node is selected do NOT over-ride
    // the default colors
    if (sel)
    return this;
    // cast to our wrapper Node class
    RollupNode node = (RollupNode) value;
    if (node.isInventory())
    if (RollupMediator.getInstance().nodeInList(node))
    setForeground(RollupTree.FOUND);
    setToolTipText("Click to find positions count");
    else
    setForeground(RollupTree.NOT_FOUND);
    setToolTipText("Inventory not in current business date");
    else
    setToolTipText("Double click to edit name");
    return this;
    } // Renderer
    Let me know if you need more examples.
    BTW
    I the TreeCellRenderer example is not public so I can add it to the bottom of the file that contains my custom JTree.

  • Help with JTree and JList

    Hi everybody!
    My problem is this:
    I have in a panel a JTree. This tree has a root and several children called GROUPs. Every GROUP has several children called MODULEs. Every MODULE have several children called RULEs.
    The JTree is already constructed with a function that I have implemented and that reads the data necessary to fill the tree.
    What I would like to get, and I do not know how, is that when I press with the mouse in "Root" I can see a list, on the right side of the tree, with all the GROUPs that it contains. Besides, when I press with the mouse in a GROUP I can see the list of MODULEs that it contains. And finally that when I press with the mouse in a MODULE I can see the RULEs that it contains.
    I think that it is done by using listeners and so on, but actually I do not understand well how it works.
    I would be very grateful whether any of you could show me a piece of code (at least some guidelines) of the function that I would have to implement. And of course, a little bit of explanation about the use of listeners and so on that are necessary to do these kind of things.
    I am a total begginer and I need your help.
    Thanks a lot in advance,
    Fran.

    Please, helpppppppppppp!!!!!!!!!!!!!!!!!!!!!!!
    :)

  • Modification of Jtree at Runtime ...Forurth Posting on this Prb..Help me

    Hello ALL:
    I am developing a swing application.The initial JTree is populated using the Sql Query(JDBC)
    My application have a JPopupItem which has a item namely"Add".
    The ADD opens a Component Display Class in the SplitPane(ScrollPane is enabled).The ADD Class has a Saving functionality (The Procees will go to the SQL Server)which will help me add a new node to the JTree.
    Can I do this...A Population of Jtree when I add a new node at Runtime and execute the Query again to populate the Jtree and my problem has to be solved using JDBC.I have to call my Sql query with the fresh value inserted into the Database when I add a value.Can I recall my Swing Constructor again with a boolean flag which would help me identify the refresh of the fresh values inserted by the user.
    Help me with how to call the Constructor(The Jtree is built using the Sql Quert initially).
    Thanking you.
    Help me..This is urgent.
    Regards
    Ritesh

    When you add the whatsit to the database, add it to the JTree also. Don't rebuild the entire tree from scratch every time; this will perform very badly when your tree becomes large.

  • Help with JTrees

    Hello,
    I have a JTree and I need it's items to display as stylized text. Or in other words, I want the listed leafs on the JTree to sometimes be bold, colored, underlined, superscript, etc. The style of each JTree leaf will be determined by the properties of a SimpleAttributeSet.
    Basically, is there a way to turn the cells that render each node into DefaultStyledDocuments so that I can call insertString( int offs, String str, AttributeSet a) on it?
    Thanks a lot for any help on this,
    - kevin

    Btw, The other arguments in the method (selected, expanded, leaf, row and hasFocus) allow you to further customize a rendered node.
    ie. if a tree's row is selected, the selected flag will be true, you should have something like:
    if(selected)
      // render it as 'selected', ie change the background color or something
    }in your getTreeCellRendererComponent() method.
    The "row" integer tells you what row in the tree you are at, so you can also customize things further using that argument.

  • JTree traversals ??? pls help!

    My quaestion is:
    I have a graphical tree (JTree) in a swing window. My task is to
    display (by text) preorder and inorder traversals of the tree in a new bottom window (by splitting the main window).
    And I also have to add listeners to be able display the traversals when I make change in the tree. (I need to use DefaultMutableTreeNode)
    I've been trying to do it for two weeks. if you have any idea please help me...

    Hi.
    starting from the point where you have a JTree which uses Default..Nodes for its internal structure, your prob can be solved like this:public void showTraversing(JTree tree) [
      // assuming JTree is a tree with a data structure
      // using DefaultMutableTreeNode as its nodes
      TreeModel tmodel = tree.getModel();
      DefaultMutableTreeNode node = (DefaultMutableTreeNode) tmodel.getRoot();
      // traverse them to the console:
      traversePreorder(node);
      traversePostordfer(node);
    // traverse recursivley in preorder
    public void traversePreorder(DefaultMutableTreeNode node) {
      if (node != null) {
        // preorder means node before children:
        System.out.println(node.toString() + " "); // or whatever you want to print
        // then process all children:
        Enumeration children = node.children();
        while (children.hasMoreElements()) {
          traversePreorder((DefaultMutableTreeNode) children.nextElement());
    // traverse recursivley in postorder
    public void traversePostorder(DefaultMutableTreeNode node) {
      if (node != null) {
        // postorder means process children first:
        Enumeration children = node.children();
        while (children.hasMoreElements()) {
          traversePreorder((DefaultMutableTreeNode) children.nextElement());
        // then the actual node:
        System.out.println(node.toString() + " "); // or whatever you want to print
    }I didn't test this code so I don't give any warranties that it works. But I'm pretty sure there are not too many bugs in there.
    Any questions? Shouldn't be that hard to reproduce.
    HTH & cheers,
    kelysar
    HTH,

  • A little help debugging a JTree

    I'm pretty much a first time JTree maker, and I can't seem to find the error in my code keeping me from adding into my categories I was hopeing someone in here would help.
    I have a vector containing objects constructed from a text file like so:
    try
       *The job of this is to read a file to make items in the
       *categories below.
      fr = new FileReader (myfile);
      br = new BufferedReader (fr);
      line = br.readLine ();
      while (line != null)
       underWho = line;
       name = br.readLine ();
       desc = br.readLine ();
       img = br.readLine ();
       subInfo.addElement (new ProSubTools (underWho, name, desc, img));
       line = br.readLine ();
    catch (IOException ioe)
       System.out.println (ioe);
    }from here I use the following method to construct my nodes, the first set is made using a String array called categories. ProSubTools is basically a container class so that I can keep info like what node to put them under (underWho), their name and so on.
    private void createNodes (DefaultMutableTreeNode top)
      DefaultMutableTreeNode category = null;
      DefaultMutableTreeNode item = null;
      for (int i = 0; i < categories.length; i++)
        category = new DefaultMutableTreeNode (categories );
    for (int j = 0; j < subInfo.size (); j++)
    { /*I know the error is in here some where*/
    /*This is supposed to make another node for the tree*/
    ProSubTools temp = (ProSubTools)subInfo.elementAt (j);
    item = new DefaultMutableTreeNode (temp.toString ());
    /*fileTo () returns a String saying where to put this node*/
    if(temp.fileTo ().equals (categories [i]))
    category.add (item);
    top.add (category);

    Turns out there was nothing wrong, apparently I saved it as my text file as Unicode. sorry

  • Hi..............I Stuk up with a problem in JTree Please, help me any one..

    Hi,
    I created a JTree where the DefaultMutableTreeNode is created at run time and for this node, the leaf items are added dynamically.....Now my problem is, I should get a popup menu when i click on the treenode particularly-----
    * Node1
    -------Node11
    -------Child1
    In this I want a popup only for the Node11 & its child elements if there is any Node2 also i don't want a popup and also for Node1 i don't want, when I am trying this I am getting the Popup to all nodes and child elements, please, help me any one who cross over this problem.............
    Thanks In Advance,
    Regards,
    Sarikakiran

    Firstly, do you know how to detect the right click? (Use a MouseListener.)
    When you receive the MouseEvent for the right-click, you can get the coordinates of the click (i.e. where on the JTree the mouse was clicked).
    You can then use JTree.getPathForLocation to get the path for the clicked node, which is a TreePath object. Use TreePath.getLastPathComponent to find which node was actually clicked on.
    Having determined which node was clicked, you can then make a decision about whether to show a popup menu.

Maybe you are looking for

  • PHP refuses to load ZendOptimizer 3.3.9

    I've got Apache and PHP running properly, however whenever the server starts I get the following error which is preventing the ZendOptimizer.so module to be loaded in : PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20060613-

  • Sales order with Compl.deliv., Lead time and Shipping date problems

    Hello, SAP gurus! We have some concerns with sales orders that won't start processing, and I'm wondering if there's anyone here who have had experience with this problem. If not, hopefully you understand this scenario. Scenario: * A salesorder with t

  • Search using categories from 2nd cat schema not working

    Hi, We're currently using 2 categorization schemas in our transactions.  However, the Category search criterion doesn't seem to work when we try to search for transactions using categories from the second categorization schema.  The same search crite

  • Create target group for contacts does not work

    Hi Experts, I am working on a Markting solution for a University with CRM 5.0. We need to contact certain Teachers in Schools (they have an orientation function for pupils that might study in the University in the future). I can segment for schools i

  • Grayshade

    hi, how to convert my color document to grayscale ? my code doesn't work set selected of (every page item of current document) to true set fill color of selection to "gray color info" I don't understang how to use the fill color object sorry for my e