Jbuttons in JTree

Hello Guys!
I have got a problem I have got a JTree with JButtons but only the childs are Buttons, pleas can you help me that the parents are also JButtons.
package com.cbm.vis.util;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import com.cbm.util.CBMIConstant;
import com.cbm.vis.cashbook.CBM_KBEntry;
import com.cbm.vis.cashbook.CBM_KBList;
import com.cbm.vis.cashbook.CBM_KBSearch;
import com.cbm.vis.cmanagment.CBM_Customerentry;
import com.cbm.vis.cmanagment.CBM_Customerdelete;
import com.cbm.vis.main.CBMMain;
*  Name:    JTree mit Buttons                            *
*  Author:  Thomas Rockenschaub                          *
*  Date:    30.12.2006                                *
*  Modified Date: 5.1.2007                                   *     
*  Version: 1.8 [Beta]                                *
*  Description: Tree um auf die diversen Funktion     *
*                      des Programms zugreifen zu k�nnen     *
public class CBMJTree
implements CBMIConstant
     /* Konstante f�r die Gr��e des JTrees im Hauptfenster */
     private static final int m_sizex = 200;
     private CBM Kassabuch[] = {
            new CBM("  KB Eintrag     "),
            new CBM("  KB Editieren  "),
            new CBM("  KB L�schen  "),
            new CBM("  KB Auflisten  "),
            new CBM("  KB Drucken   ") };
     private CBM Kundenverwaltung[] = {
             new CBM("  Kundeneintrag      "),
             new CBM("  Kunden Editieren  "),
             new CBM("  Kunden L�schen  "),
             new CBM("  Kunden Auflisten  "),
             new CBM("  Kunden Drucken   ") };
     private CBM Administrator[] = {
             new CBM("  AD Einstellungen "),
             new CBM("  AD Benutzer          "),
             new CBM("  AD Login/Logout   "),
             new CBM("  AD Informationen ")};
     private Vector KBVector;
     private Vector KVVector;
     private Vector ADVector;
     private Vector rootVector;
     private JTree tree;
     private JScrollPane scroll;
   public CBMJTree()
       KBVector = new NameVector("Kassabuch", Kassabuch);
       KVVector = new NameVector("Kundenverwaltung", Kundenverwaltung);
       ADVector = new NameVector("Administrator", Administrator);
       Object rootNodes[] = { KBVector, KVVector, ADVector };
       rootVector = new NameVector("Root", rootNodes);
       tree = new JTree(rootVector);
       TreeCellRenderer renderer = new CBMCellRenderer();
       tree.setCellRenderer(renderer);
       scroll = new JScrollPane(tree);
       scroll.setMinimumSize(new Dimension(m_sizex,m_fgry));
   public Component getJScrollPane()
        return scroll;
class CBM
     String title;
     public CBM(String title)
       this.title = title;
     public String getTitle()
       return title;
class CBMCellRenderer
implements TreeCellRenderer
      private JLabel titleLabel;
     private boolean choose=true;
     private int value1, value2;
     private JPanel renderer;
     private DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();
     private Color backgroundSelectionColor;
     private Color backgroundNonSelectionColor;
     private JButton button;
     public CBMCellRenderer()
         renderer = new JPanel(new FlowLayout(FlowLayout.RIGHT,6,6));
        titleLabel = new JLabel(" ");
        titleLabel.setForeground(Color.blue);
        button=new JButton();
        renderer.add(button);
        backgroundSelectionColor = defaultRenderer.getBackgroundSelectionColor();
        backgroundNonSelectionColor = defaultRenderer.getBackgroundNonSelectionColor();
     public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)
        Component returnValue = null;
        if ((value != null) && (value instanceof DefaultMutableTreeNode))
           Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
           if (userObject instanceof CBM)
              CBM book = (CBM) userObject;
              button.setText(book.getTitle());
              if (selected)
                  renderer.setBackground(backgroundSelectionColor);
                 String react = book.getTitle();
                  if(choose==false)
                       if(react.equals("  KB Eintrag     "))
                            value2=1;
                       else if(react.equals("  KB Editieren  "))
                            value2=2;
                       else if(react.equals("  KB L�schen  "))
                            value2=3;
                       else if(react.equals("  KB Drucken   "))
                             value2=4;
                       else if(react.equals("  KB Auflisten  "))
                                  value2=5;
                       else if(react.equals("  Kundeneintrag      "))
                            value2=6;
                       else if(react.equals("  Kunden Editieren  "))
                            value2=7;
                       else if(react.equals("  Kunden L�schen  "))
                            value2=8;
                       else if(react.equals("  Kunden Drucken   "))
                             value2=9;
                       else if(react.equals("  Kunden Auflisten  "))
                                  value2=10;
                       else if(react.equals("  AD Einstellungen "))
                            value2=11;
                       else if(react.equals("  AD Benutzer          "))
                            value2=12;
                       else if(react.equals("  AD Login/Logout   "))
                            value2=13;
                       else if(react.equals("  AD Informationen "))
                             value2=14;
                       if(value1!=value2)
                           choose=true;
                 //Hier kann jetzt auf die Buttons reagiert werden
                 if(choose==true)
                      if(react.equals("  Kundeneintrag      "))
                           System.out.println(""+react);
                           CBM_Customerentry Custentry=new CBM_Customerentry();
                           CBMMain.setrightPanelComponent2(Custentry.getMainJPanel());
                           CBMMain.setrightPanelComponent3(Custentry.getJButtonPanel());
                           value1=6;
                           choose=false;
                      }else if(react.equals("  Kunden Editieren  "))
                           System.out.println(""+react);
                           value1=7;
                           choose=false;
                      }else if(react.equals("  Kunden L�schen  "))
                           System.out.println(""+react);
                           /*CBM_Customerdelete Custdelete=new CBM_Customerdelete();
                           CBMMain.setrightPanelComponent2(Custdelete.getMainJPanel());
                           CBMMain.setrightPanelComponent3(Custdelete.getJButtonPanel());*/
                           value1=8;
                           choose=false;
                      }else if(react.equals("  Kunden Auflisten  "))
                           System.out.println(""+react);
                           value1=10;
                           choose=false;
                      }else if(react.equals("  Kunden Drucken   "))
                           System.out.println(""+react);
                           value1=9;
                           choose=false;
                      }else if(react.equals("  KB Eintrag     "))
                           System.out.println(""+react);
                           CBM_KBEntry entry=new CBM_KBEntry();
                           CBMMain.setrightPanelComponent2(entry.getMainJPanel());
                           CBMMain.setrightPanelComponent3(entry.getJButtonPanel());
                           value1=1;
                           choose=false;
                      }else if(react.equals("  KB Editieren  "))
                           System.out.println(""+react);
                           CBM_KBSearch entry=new CBM_KBSearch();
                           CBMMain.setrightPanelComponent2(entry.getMainJPanel());
                           CBMMain.setrightPanelComponent3(entry.getJButtonPanel());
                           value1=2;
                           choose=false;
                      }else if(react.equals("  KB L�schen  "))
                           CBM_KBSearch entry=new CBM_KBSearch();
                           CBMMain.setrightPanelComponent2(entry.getMainJPanel());
                           CBMMain.setrightPanelComponent3(entry.getJButtonPanel());
                           System.out.println(""+react);
                           value1=3;
                           choose=false;
                      }else if(react.equals("  KB Auflisten  "))
                           CBM_KBList entry=new CBM_KBList();
                           CBMMain.setrightPanelComponent2(entry.getMainJPanel());
                           //CBMMain.setrightPanelComponent3(entry.getJButtonPanel());
                           System.out.println(""+react);
                           value1=5;
                           choose=false;
                      }else if(react.equals("  KB Drucken   "))
                           System.out.println(""+react);
                           value1=4;
                           choose=false;
                      }else if(react.equals("  AD Einstellungen "))
                           System.out.println(""+react);
                           value1=11;
                           choose=false;
                      }else if(react.equals("  AD Benutzer            "))
                           System.out.println(""+react);
                           value1=12;
                           choose=false;
                      }else if(react.equals("  AD Login/Logout   "))
                           System.out.println(""+react);
                           value1=13;
                           choose=false;
                      }else if(react.equals("  AD Informationen "))
                           System.out.println(""+react);
                           value1=14;
                           choose=false;
              else
                 renderer.setBackground(backgroundNonSelectionColor);
              renderer.setEnabled(tree.isEnabled());
              returnValue = renderer;
        if (returnValue == null)
           returnValue = defaultRenderer.getTreeCellRendererComponent(tree,value, selected, expanded, leaf, row, hasFocus);
        return returnValue;
class NameVector
extends Vector
     private static final long serialVersionUID = 1L;
     String name;
     public NameVector(String name)
       this.name = name;
     public NameVector(String name, Object elements[])
        this.name = name;
        for (int i = 0, n = elements.length; i < n; i++)
           add(elements);
public String toString()
return "[" + name + "]";

To post code, use the code tags -- [code]Your Code[/code]will display asYour CodeOr use the code button above the editing area and paste your code between the tags it generates.
db

Similar Messages

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

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

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

  • Different look of button in jtree or jtable (windows/linux)

    Hi.
    I have jbutton on jtree(in jtable is the same problem) it looks like this on linux: http://mikel.pl/button.jpg .
    On windows eveyrthink is ok. I tried to set RaisedBevelBorder but in this case on windows button looks awful. Is any trick to get the same look of button without checking what system is running?

    Yes and no. Linux and Windows use different LookAndFeels by default, meaning the buttons are painted differently. Just setting the same border will not do in this case. The only way of having the application look exactly the same on both platforms is to manually set a LookAndFeel available on both systems. This should be the case for the MetalLookAndFeel, the SynthLookAndFeel and, I believe, for the Linux LookAndFeels as well.

  • Trying to create a simple example. Need Help!

    I'm trying to create a very simlpe examlpe using Swing components to illustrate a MVC architecture.
    I have a JFrame containing a JTree and a JButton.
    What I'd like to happen is when I click the JButton the JTree model is changed in some fashion and the the view is refreshed due to the models change.
    If anyone out there has a simple example of any MVC architecture involving Swing components I'd love to see it.
    Thx

    Sure, look at any of the Sun tutorials. For example, look in your API documentation for JTree; it has a link to a tutorial about how to use JTree.

  • Jcomponent vs jframe

    hey all, im kinda new in java programming but i like this language alot, i was trying to look online for some GUI code, well i found a lot of sample swing code, some of them extends JComponent while the other extends JFrame...
    what exactly is the difference, please ellaborate and be clear as much as you can...
    thnx in advance

    A JFrame is a top-level window. Usually, your GUI application will have one single JFrame.
    JComponent is the base-class for all widgets, such as JButton, JLabel, JTree, etc. You add your widgets to a container, e.g. a JPanel (which also derives from JComponent btw), which at some point is added, directly or indirectly, to your top-level frame.
    code, some of them extends JComponent while the other
    extends JFrame...It's not very often that you actually need to extend a JComponent, and there is almost never a good reason to extend JFrame.

  • AWT Canvas vs. Swing "glass pane"

    Hello again world.
    The book I've been reading led me down the Swing path but I thought I would go back and take a closer look at the AWT package.
    Is an AWT Canvas analogous to a Swing JRootPane's glass pane?
    Thank you one and all.
    Ciao for now.

    No, not really.
    1) A Canvas is specifically for drawing. There's really no other purpose for it to exist. It's not a container, like Panel. Although, you can use AWT Panel in place of a Canvas, there'd be nothing wrong with that.
    A glasspane has a purpose in a JFrame or other top-level Swing container. It's there to be shown, but often transparently, on top of all other components in that top-level container. You can make the glasspane be any class, yes, but generally it's going to be a JPanel or subclass, and you could paint on it if you override the paintComponent method, or add mouse listeners to intercept mouse events (when it's visible).
    That you can draw on a Canvas or a glasspane component is irrelevant. One can can subclass JButton or JTree or AWT List or any other AWT or Swing component and override the paint or paintComponent method and do custom painting on it. The ability to paint on components is universal. But you wouldn't use a JButton or AWT Button for a glasspane.
    2) You don't want to use Canvas as a glass pane (or any AWT component) if you want the pane to be transparent. AWT components cannot be transparent, so if the component is visible, it'll block out anything under it. It's the whole issue of AWT's heavyweight components vs Swing's lightweight components.

  • Disable all components AND subcomponents

    I have a bunch of JButtons, JText, JTree, etc. in a JPanel and I want to disable/grey-out all of them. But some of the JComponents are in a Box. They don't get disabled. The code I am using now:
         public void setEditable(boolean bool) {
              for (Component component: getComponents()) {
                   component.setEnabled(bool);
    So the above works for all the components that are not in the Box
    I ended up doing the below (checks if the component is a Box and if it is, iterate through that enabling/disableing JComponents):
         public void setEditable(boolean bool) {
              for (Component component: getComponents()) {
                   component.setEnabled(bool);
                   if (component.getClass().toString().equals("class javax.swing.Box")) {
                        for(Component subComponent: ((Box)component).getComponents()) {
                             subComponent.setEnabled(bool);
    So big question is, is there some better way of doing this, or someway which is more generic?

    Well you could extend Box and override the setEnabled method to call setEnabled of all it's components, and then use that as your Box instead.
    But I have a couple of suggestions regarding the code you posted.
    1. You should use instanceof operator to check whether the component is an instance of Box
    2. You don't handle the case when there's a Box within a Box.
    e.g.,
    public void setEditable(boolean editable) {
        for (Component c : getComponents()) {
            setEditable(c, editable);
    private void setEditable(Component c, boolean editable) {
        c.setEnabled(editable);
        if (c instanceof javax.swing.Box) {
            for (Component subC : ((javax.swing.Box)c).getComponents())
                setEditable(subC, editable);
    }

  • JTree and JButton in node.

    Helo.
    I've a question regarding JTree component. I was wondering if it is possible at all.
    I want to build JTree component with JButton(JPanel) in each node, for example:
    RootNode
    |
    ---String [JButton][JButton]
    |
    ---String [JButton][JButton]
    Is there possibility to put JPanel into children node.
    Maybe anyone did do this before?
    Thanks in advance for any help.
    Regards

    This is possible. You'll have to take a look at TreeCellRenderer and TreeCellEditor, and maybe the tutorial at http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html . Basically, both interfaces allow you to return arbitrary components for rendering / editing tree nodes. The default implementation is based on JLabels, but you can use complex panels with multiple child components as well.

  • Jtree: Can I add JButtons (that actualy work) to leafnodes?

    Basically, I have added a couple of JButtons to each node of the tree by creating a DefaultTreeCellRenderer. The buttons are rendered fine, but do not respond at all to mouse clicks. I think this is because the JTree only allows node content to be changed when it is in edit mode (for example, changing the DefaultTreeCellEditor would allow you to implement a JButton).
    Please could you tell me if it is possible to implement JButtons into a JTree and achieve the result I want � or is this not possible.
    Thanks for your help.

    Have you tried adding a tree selection listener to the tree? This will allow you to respond to tree node selections. If that doesn't work your suggestion of using a DefaultTreeCellEditor may work.

  • How do I use JPanel as a leaf in JTree ?

    Hi All,
    I am a bit of a newbie and I've been trying to change the behavior of my application.
    I have a JTree that I now want to change the rendering of a leaf to be a JPanel. The JPanel will have a couple of JButtons and some text and the user can interact with the JButtons. I was successful in creating the JPanel, adding the buttons and then making my own TreeCellRenderer. Everything displays fine, but the user can not interact with the JButtons, whenever I click on a button in the leaf, the whole leaf is highlighted - I suppose I should not be surprised because this is probably behaving just a cell in a JTree should.
    So I searched the forums and used Google and have found several examples of people using JCheckBox as nodes/leaf(s) in a JTree but none with a JPanel as a leaf. I took one of the check box demos from here ( [http://www.coderanch.com/t/330630/Swing-AWT-SWT-JFace/java/add-swing-component-tree]) and then hacked it a bit but am stuck with the following error :
    Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.JPanel
    which is pointing to the line with JPanel temp2 = (JPanel) temp.getUserObject();
    Does anyone have either some code or suggestions to accomplish a leaf as a JPanel with some buttons ?
    Thanks in advance !
    import javax.swing.*;*
    *import javax.swing.tree.*;
    import java.awt.event.*;*
    *import java.awt.*;
    public class treedemo1 extends JFrame {
        public treedemo1() {
            super("TreeDemo");
            setSize(1500, 1500);
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());
            customLeafPanel cp1 = new customLeafPanel();
            customLeafPanel cp2 = new customLeafPanel();
            customLeafPanel cp3 = new customLeafPanel();
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Query Results");
            DefaultMutableTreeNode n1 = new DefaultMutableTreeNode(cp1, false);
            DefaultMutableTreeNode n2 = new DefaultMutableTreeNode(cp2, false);
            DefaultMutableTreeNode n3 = new DefaultMutableTreeNode(cp3, false);
            root.add(n1);
            root.add(n2);
            root.add(n3);
            JTree tree = new JTree(root);
            p.add(tree, BorderLayout.NORTH);
            getContentPane().add(p);
            TestRenderer tr = new TestRenderer();
            tree.setEditable(false);
            tree.setCellRenderer(tr);
        public class customLeafPanel extends JPanel {
            public customLeafPanel() {
                JPanel clpPanel = new JPanel();
                JButton helloJButton = new JButton("Hello");
                this.add(helloJButton);
        public class TestRenderer implements TreeCellRenderer {
            transient protected Icon closedIcon;
            transient protected Icon openIcon;
            public TestRenderer() {
            public Component getTreeCellRendererComponent(JTree tree,
                    Object value,
                    boolean selected,
                    boolean expanded,
                    boolean leaf,
                    int row,
                    boolean hasFocus) {
                DefaultMutableTreeNode temp = (DefaultMutableTreeNode) value;
                JPanel temp2 = (JPanel) temp.getUserObject();
                return temp2;
            public void setClosedIcon(Icon newIcon) {
                closedIcon = newIcon;
            public void setOpenIcon(Icon newIcon) {
                openIcon = newIcon;
        public static void main(String args[]) {
            JFrame frame = new treedemo1();
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            frame.pack();
            frame.setVisible(true);
    }

    Thank you TBM and DB for your replies ! Adding TBM's code does indeed fix the JPanel issue and as TBM indicated this does not actually solve my ultimate problem (Can I give you each 1/2 the Duke points?)
    As a newbie, I am still learning and DB pointed out that "You can however interact with an editor". So after reading the suggested tutorials and looking back at the example code that I hacked. I added the cellEditor back in and it WORKS ! Its funny, I deleted that bits of code from the example, assuming the cellEditor allows you to "edit" (ie change), not interact with it (symantics I guess)
    Thanks again guys for pointing this newbie in the right direction. Frankly I am somewhat surprised that I could finally begin to read and understand what the tutorial and suggestions are telling me ! What is one step up from a newbie ?
    unfortunately I can not post the code because the length of the message is > 5000 :(

  • Problem with JTree.isExpanded()

    Working with a JTree, I encountered into a strange behavior - I hope someone could explain me...
    For exporting a tree I need the information whether nodes are expanded or not.
    The first strange thing is that the root always seems to be collapsed - but this I can handle somehow.
    The problem is, that a expanded node containing a leaf, is reported as collapsed - but it is not. Why?
    Here the output of a expand-checking method, which prints the state of the node and its parents.
    (the "+" indicates a expanded node, the "-" indicated a collapsed node)
    + - Abasdf
    + - EP/asdf
    + - - Prosadf
    + - - - Altasdf
    + - - - - V1sadf
    + - - - - - 059asdf
    + - - - - - - 059asdf
    + - - - - - - + 059asdf
    + - - - - - - + + this_is_a_leafWhy is the expanded node containing the leaf reported as collapsed?
    I'm using the following for checking if a node is expanded:
    view.isExpanded(node.getIndex())I also tried this - with the same wrong result:
    view.isExpanded(view.getPathForRow(node.getIndex()))Any hint is highly appretiated.

    I was not able to reproduce your problemimport javax.swing.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeNode;
    import java.util.Random;
    import java.util.Enumeration;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    public class HamsterChipsyTest extends JPanel {
         private static final Random RANDOM = new Random(System.currentTimeMillis());
         private JTree theTree;
         private DefaultTreeModel theTreeModel;
         private DefaultMutableTreeNode theRoot;
         public HamsterChipsyTest() {
              super(new BorderLayout());
              theRoot = createRandomNode();
              addNodes(theRoot, 0, 2);
              theTreeModel = new DefaultTreeModel(theRoot);
              theTree = new JTree(theTreeModel);
              add(new JScrollPane(theTree), BorderLayout.CENTER);
              add(new JButton(new AbstractAction("dump nodes' extension state") {
                   public void actionPerformed(ActionEvent e) {
                        dumpExtensionState(theRoot);
              }), BorderLayout.NORTH);
         private void dumpExtensionState(DefaultMutableTreeNode aTreeNode) {
              TreeNode[] path = aTreeNode.getPath();
              for (int i = 0; i < path.length; i++) {
                   System.out.print('-');
              System.out.println(" " + aTreeNode.getUserObject().toString() + " " + theTree.isExpanded(new TreePath(path)));
              Enumeration children  = aTreeNode.children();
              while(children.hasMoreElements()) {
                   DefaultMutableTreeNode child = (DefaultMutableTreeNode)children.nextElement();
                   dumpExtensionState(child);
         private static void addNodes(DefaultMutableTreeNode aParent, int aCurrentDepth, int aMaxDepth) {
              if (aCurrentDepth >= aMaxDepth) return;
              int nodeCount = RANDOM.nextInt(3);
              for (int i = 0; i < nodeCount + 1; i++) {
                   DefaultMutableTreeNode child = createRandomNode();
                   aParent.add(child);
                   addNodes(child, aCurrentDepth + 1, aMaxDepth);
         private static DefaultMutableTreeNode createRandomNode() {
              char[] chars = new char[5];
              for (int i = 0; i < chars.length; i++) {
                   chars[i] = (char)('a' + RANDOM.nextInt(26));
              return new DefaultMutableTreeNode(new String(chars));
         public static void main(String[] args) {
              final JFrame frame = new JFrame(HamsterChipsyTest.class.getName());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new HamsterChipsyTest());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.pack();
                        frame.show();
    }

  • Mouse over JButton

    I have an 10 x 10 array of JButtons in my project. I was just wondering how do i find out which button the mouse cursor is over at any given time?
    I was trying to get x y mouse coordinates but how do i know over which JButton I am?
    Thanks for any advice
    Regards

    Could anybody help me with answer: How could I execute below method:
    public void mouseMoved(MouseEvent e) {
              System.out.println("Mouse over Button");
         }without clicking on the button. I have MouseListener on each button. I can exetue this method only when i'm clicking on button. What's wrong with my code? I wanna execute this method when my mouse is over the button :-(. Could help me with my example?
    thanks in advance.
    regards.
    package gui;
    import java.awt.Component;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.util.ArrayList;
    import java.util.EventObject;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTree;
    import javax.swing.event.ChangeEvent;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreeCellEditor;
    import javax.swing.tree.TreeCellRenderer;
    public class TreeSample {
         JTree tree = null;
         CheckBoxNodeRenderer renderer;
         public void showTree() {
              JFrame frame = new JFrame("Tree");
              ArrayList<Object> ipDevice = new ArrayList<Object>();
            ipDevice.add("IP Device");
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(new CheckBoxNode("IP Device", false));
            rootNode.add(node);
            tree = new JTree(rootNode);
            renderer = new CheckBoxNodeRenderer();
            tree.setCellRenderer(renderer);
            tree.setCellEditor(new CheckBoxNodeEditor(tree));
            tree.setEditable(true);
            frame.setSize(400,400);
            frame.add(tree);
            frame.setVisible(true);
         public static void main(String args[]) {
              System.out.println("Test");
              TreeSample ts = new TreeSample();
              ts.showTree();
    class CheckBoxNodeRenderer implements TreeCellRenderer {
        private JButton leafRenderer = new ButtonCreator("TEST");
        protected JButton getLeafRenderer(){
            return leafRenderer;
        public CheckBoxNodeRenderer() {
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                boolean selected, boolean expanded, boolean leaf, int row,
                boolean hasFocus) {
            Component returnValue;
            returnValue = leafRenderer;
            return returnValue;
    class CheckBoxNodeEditor extends AbstractCellEditor implements TreeCellEditor, MouseMotionListener {
        CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();
        ChangeEvent changeEvent = null;
        JTree tree1;
        DefaultMutableTreeNode editedNode;
        public CheckBoxNodeEditor(JTree tree) {
            this.tree1 = tree;
        public Object getCellEditorValue() {
            JButton checkbox = renderer.getLeafRenderer();
            return checkbox;
        public boolean isCellEditable(EventObject event) {
            return true;
        public boolean shouldSelectCell(EventObject ev) {
             return true;
        public Component getTreeCellEditorComponent(final JTree tree, Object value,
                boolean selected, boolean expanded, boolean leaf, int row) {
            System.out.println("GetTree");
            Component editor = renderer.getTreeCellRendererComponent(tree, value,
                    true, expanded, true, row, true);
            return editor;
         public void mouseDragged(MouseEvent e) {
         public void mouseMoved(MouseEvent arg0) {
    class CheckBoxNode {
        String text;
        boolean selected;
        public CheckBoxNode(String text, boolean selected) {
            this.text = text;
            this.selected = selected;
        public boolean isSelected() {
            return selected;
        public void setSelected(boolean newValue) {
            selected = newValue;
        public String getText() {
            return text;
        public void setText(String newValue) {
            text = newValue;
    class ButtonCreator extends JButton implements MouseMotionListener {
         public ButtonCreator() {
              this.addMouseMotionListener(this);
         public ButtonCreator(String p_name) {
              this.setText(p_name);
              this.addMouseMotionListener(this);
         public void mouseDragged(MouseEvent e) {
         public void mouseMoved(MouseEvent e) {
              System.out.println("Mouse over Button");
    }

  • JTree Inserting Problem

    Please help me ..
    i have write a code ..which is when the user clicks the button...
    a jtree table will come and the values inside the jtree will be filled by the contents of the selected items in the form...
    but my problem is jtree only is comming
    i created the object class ... but ...
    the initialisation is not happening...
    plz check the code below .. this is my class
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class Reservation extends JFrame implements ItemListener,ActionListener{
         JComboBox fromCity = null;
         JComboBox toCity = null;
         JComboBox dDay = null;
         JComboBox dMonth = null;
         JComboBox dYear = null;
         JComboBox rDay = null;
         JComboBox rMonth = null;
         JComboBox rYear = null;
         JComboBox adult = null;
         JComboBox Cabin = null;
         JFrame table;
         public Reservation()
              setSize(600,400);
              JPanel p = new JPanel();
              //getContentPane().setLayout(new BorderLayout());
              GridBagLayout gbl = new GridBagLayout();
              GridBagConstraints gbc = new GridBagConstraints();
              p.setLayout(gbl);
              String []cities = {"New York","Chicago","Miami","Pittsburgh","Memphis","New Orleans"};
              String [] days={"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","27","28","29","30","31"};
              String [] months = {"January","Feburary","March","April","May","June","July","August","September","October","November","December"};
              String [] year = {"2006","2007"};
              String [] adt = {"1","2","3","4"};
              String [] cab = {"Buisness","Economy"};
              fromCity = new JComboBox(cities);
              fromCity.setSelectedIndex(0);
              toCity = new JComboBox(cities);
              toCity.setSelectedIndex(0);
              dDay = new JComboBox(days);
              dMonth = new JComboBox(months);
              dYear = new JComboBox(year);
              rDay = new JComboBox(days);
              rMonth = new JComboBox(months);
              rYear = new JComboBox(year);
              adult = new JComboBox(adt);
              Cabin = new JComboBox(cab);
              JLabel frmCity = new JLabel("From");
              frmCity.setLabelFor(fromCity);
              JLabel tCity = new JLabel("To");
              tCity.setLabelFor(tCity);
              JLabel dDate = new JLabel("Departure Date");
              dDate.setLabelFor(dDate);
              JLabel rDate = new JLabel("Return Date");
              rDate.setLabelFor(rDate);
              JLabel Psg = new JLabel("Pasengers");
              Psg.setLabelFor(Psg);
              JLabel Adults = new JLabel("Adults");
              Adults.setLabelFor(Adults);
              JLabel cabin = new JLabel("Cabin");
              cabin.setLabelFor(cabin);
              JLabel search = new JLabel("Search By");
              search.setLabelFor(search);
              JRadioButton ROneWay = new JRadioButton("One Way");
              JRadioButton RRoundTrip = new JRadioButton("Round Trip");
              JButton searchbutton = new JButton("Date");
              ButtonGroup group = new ButtonGroup();
              group.add(ROneWay);
              group.add(RRoundTrip);
              gbc.gridx = 0;
              gbc.gridy = 0;
              gbc.insets = new Insets(0,30,0,0);
              p.add(frmCity,gbc);
              gbc.gridx =1;
              gbc.gridy = 0;
              gbc.insets = new Insets(0,30,0,0);
              p.add(fromCity,gbc);
              gbc.gridx =0;
              gbc.gridy = 1;
              gbc.insets = new Insets(0,30,0,0);
              p.add(tCity,gbc);
              gbc.gridx =1;
              gbc.gridy = 1;
              gbc.insets = new Insets(10,30,0,0);
              p.add(toCity,gbc);
              gbc.gridx = 0;
              gbc.gridy = 2;
              gbc.insets = new Insets(10,50,0,0);
              p.add(ROneWay,gbc);
              gbc.gridx = 1;
              gbc.gridy = 2;
              gbc.insets = new Insets(10,30,0,0);
              p.add(RRoundTrip,gbc);
              gbc.gridx = 1;
              gbc.gridy = 3;
              gbc.insets = new Insets(0,0,0,0);
              p.add(dDate,gbc);
              gbc.gridx = 0;
              gbc.gridy = 4;
              p.add(dDay,gbc);
              gbc.gridx = 1;
              gbc.gridy = 4;
              p.add(dMonth,gbc);
              gbc.gridx = 2;
              gbc.gridy = 4;
              p.add(dYear,gbc);
              gbc.gridx = 1;
              gbc.gridy = 5;
              gbc.insets = new Insets(0,0,0,0);
              p.add(rDate,gbc);
              gbc.gridx = 0;
              gbc.gridy = 6;
              p.add(rDay,gbc);
              gbc.gridx = 1;
              gbc.gridy = 6;
              p.add(rMonth,gbc);
              gbc.gridx = 2;
              gbc.gridy = 6;
              p.add(rYear,gbc);
              gbc.gridx = 1;
              gbc.gridy = 7;
              p.add(Psg,gbc);
              gbc.gridx = 0;
              gbc.gridy = 8;
              p.add(Adults,gbc);
              gbc.gridx = 1;
              gbc.gridy = 8;
              p.add(adult,gbc);
              gbc.gridx = 0;
              gbc.gridy = 9;
              p.add(cabin,gbc);
              gbc.gridx = 1;
              gbc.gridy = 9;
              gbc.insets = new Insets(10,0,0,0);
              p.add(Cabin,gbc);
              gbc.gridx = 0;
              gbc.gridy = 10;
              p.add(search,gbc);
              gbc.gridx = 1;
              gbc.gridy = 10;
              gbc.insets = new Insets(10,0,0,0);
              p.add(searchbutton,gbc);
              getContentPane().add(p);
              fromCity.addItemListener(this);
              toCity.addItemListener(this);
              dDay.addItemListener( this);
              dMonth.addItemListener( this);
              dYear.addItemListener(this);
              adult.addItemListener(this);
              Cabin.addItemListener(this);
              searchbutton.addActionListener(this);
              //Jtable form
              table = new JFrame();
              Container container;
              container = table.getContentPane();
              JPanel jpanel = new JPanel(new GridLayout(2,1));
              container.setLayout(new GridLayout(2,1));
              JLabel l1 = new JLabel("Departure Journey");
              l1.setLabelFor(l1);
              container.add(l1);
              final String[] colHeads = {"","Flightno","Date","Departure Time","Arrival Time","Flight","Duration","Fare"};
              final Object[ ][ ] data = new Object[10][10];
              JTable table = new JTable(data,colHeads);
              int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;     
              int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
              JScrollPane jsp = new JScrollPane(table,v,h);
              container.add(jsp,BorderLayout.CENTER);
         String ffcity,ttcity,dday,dmon,dyear,adt,cab;
         public void itemStateChanged(ItemEvent e)
              ffcity = (String)fromCity.getSelectedItem();
              ttcity = (String)toCity.getSelectedItem();
              dday = (String)dDay.getSelectedItem();
              dmon = (String)dMonth.getSelectedItem();
              dyear = (String)dYear.getSelectedItem();
              adt = (String)adult.getSelectedItem();
              cab = (String)Cabin.getSelectedItem();
         public void actionPerformed(ActionEvent ae)
         if(ae.getActionCommand() == "Date")
              try
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              Connection con = DriverManager.getConnection("jdbc:odbc:ds","sa", "");
              PreparedStatement stmt = con.prepareStatement("select ifno,vdtime,vatime,vdate1,vdate2,vdate3,efare from airways where fcity = ? and tcity = ? and vdate1 = ? and vdate2 = ? and vdate3 = ?");
              stmt.setString(1,ffcity);
              stmt.setString(2,ttcity);
              stmt.setString(3,dday);
              stmt.setString(4,dmon);
              stmt.setString(5,dyear);
              ResultSet d = stmt.executeQuery();
              /* int count=0;
              while(d.next())
              {count++;
              int i = 0;*/
              while(d.next())
              /*for(int j =1;j<=7;j++)
              data[i][j] = rs.getString(j);
              System.out.println(" " + data[i][j]);
              }i++;*/
              System.out.println(d.getInt(1));
              System.out.println(d.getDouble(2));
              catch(Exception ex)
                   System.out.println("Error occurred");
                   System.out.println("Error:"+ex);
              table.setVisible(true);
              table.setSize(300,200);
         private static void createAndShowGUI()
              JFrame.setDefaultLookAndFeelDecorated(true);
              Reservation r=new Reservation();
              JFrame frame = new JFrame("Reservation Form");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //r.pack();
              r.setVisible(true);
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Runnable(){
                   public void run()
                        createAndShowGUI();
    in this object creation is not happening
    when i run this code ...
    only jtree is comming..
    how can i make it the values of seceted items to come in table
    i commented the parts that having error..
    when u uncomment it u will get the problem of this code

    please anyone

  • Buttons not working in jTree cells

    I have modified the defaultTreeCellRenderer to include a jButton and a Label on certain cells. Unfortunately I cannot click on the button. Clicking the button selects that row in the tree, which is fine, but it doesn't send the action on to the button. The Button doesn't depress and the buttons action listener isn't called. Anyone have any ideas?
    Thanks

    Renderers just create a picture of a component, they do not cause the component to actually appear. A cell in JTree cannot behave the way a JButton does. You can simulate a JButton to an extent, by painting it in a depressed state if the node is selected, but you cannot use that component for any kind of action processing.
    Remember that your renderer is never really added to your GUI - the component is used only to make it paint itself inside the JTree component. This is what allows you, for example, to use only one instance of a renderer for all the nodes in a tree.
    Mitch Goldstein
    Author, Hardcore JFC (Cambridge Univ Press)
    [email protected]

  • 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

Maybe you are looking for

  • Differing CMYK in Acrobat and Photoshop

    I read different CMYK values for the same PDF file in Acrobat and Photoshop. (Acrobat 9 and Photoshop CS4) I read the colours in Photoshop after opening the file as 16-bit CMYK. I read the colours for the same PDF file in Acrobat in Output Preview (P

  • Access Web Dynpro Java application through direct URL

    Hi Guys, we have a requirement that there is a link in web dynpro abap screen, click on it will open a new ie window running web dynpro java application, so what i did is i have given direct url link for that web dynpro java application: as this: htt

  • When creating a merged document the images seem to lose their quality

    When I create a merged document, the images on the master pages seem to lose their quality, any thoughts why? Is there anyway I can prevent this. Example: becomes

  • Intermittent Routing between Shared IP Zones

    I've setup a single machine with zones for apache and mail services which use the global zone's external data link. I've setup the zones as shared-ip zones: zonename: apache net:      address: 192.168.0.1/24      physical: bge1      defrouter not spe

  • IPad taking a long time to recharge

    When iPad battery is down to around 30% or less and I recharge, it takes a long time to recharge. Overnight, it charges maybe 10-15% and the charger itself becomes hot. I understand it should take about 3 hours to recharge to 100%. That's seldom happ