How to Create a Simple Tree Using GXT(Ext GWT) TreePanel

TreePanel is another powerful UI tools provide by GXT.  It has expand-collapse functionality. You can add context menu or can add filter functionality with the TreePanel very easily. Here i describe every steps of creating a simple basic Tree using GXT in detail.

First create a new project named GxtBasicTree and add GXT library in the project. The tree node objects must possess the functionality of BaseTreeModel of GXT. In my example the leaf node objects are of EmployeeTreeNode class and parent node objects are of Folder class. Both of the classes extend BaseTreeModel class. Here is the code for the Employee class.

package com.ratul.GxtBasicTree.client.model;

import java.util.Date;

import com.extjs.gxt.ui.client.data.BaseTreeModel;

public class EmployeeTreeNode extends BaseTreeModel {
 private static final long serialVersionUID = 1L;

public EmployeeTreeNode() {
  }

  public EmployeeTreeNode(String name, double salary, Date joiningdate) {
    set("name", name);
    set("salary", salary);
    set("joiningdate", joiningdate);
  }

  public Date getJoiningdate() {
    return (Date) get("joiningdate");
  }

  public String getName() {
    return (String) get("name");
  }

  public double getSalary() {
    Double salary = (Double) get("salary");
    return salary.doubleValue();
  }
  public String toString() {
    return getName();
  }
}
As i have said previously the objects of the Folder class can be parent node for the Tree. So this class should have the functionality of adding children nodes. The constructor with a String and an Array of BaseTreeModel object serves the purpose. Here is the code for the Folder class.



package com.ratul.GxtBasicTree.client.model;

import java.io.Serializable;

import com.extjs.gxt.ui.client.data.BaseTreeModel;

public class Folder extends BaseTreeModel implements Serializable {
 private static final long serialVersionUID = 1L;
private static int ID = 0;
  
  public Folder() {
    set("id", ID++);
  }

  public Folder(String name) {
    set("id", ID++);
    set("name", name);
  }

  public Folder(String name, BaseTreeModel[] children) {
    this(name);
    for (int i = 0; i < children.length; i++) {
      add(children[i]);
    }
  }

  public Integer getId() {
    return (Integer) get("id");
  }

  public String getName() {
    return (String) get("name");
  }

  public String toString() {
    return getName();
  }
}

Now populate a root node containing all the child nodes by using the above two classes in the getTreeModel methodh of the TestData class.
package com.ratul.GxtBasicTree.client;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.ratul.GxtBasicTree.client.model.Employee;
import com.ratul.GxtBasicTree.client.model.Folder;

public class TestData {

  public static Folder getTreeModel() 
  {
     DateTimeFormat f = DateTimeFormat.getFormat("yyyy-mm-dd");
  Folder[] folders = new Folder[] {
   new Folder("General Administration", new Folder[] {
    new Folder("General Manager", new EmployeeTreeNode[] {
     new EmployeeTreeNode("Hollie Voss", 150000, f.parse("2006-05-01")),
     new EmployeeTreeNode("Heriberto Rush", 150000,f.parse("2007-08-01")), }),
    new Folder("Executive", new EmployeeTreeNode[] {
     new EmployeeTreeNode("Christina Blake", 45000,f.parse("2008-11-01")),
     new EmployeeTreeNode("Chad Andrews", 45000, f.parse("2008-07-01")), }), }),
 
   new Folder("Information Technology",new Folder[] {
    new Folder("Senior S/W Engineer",new EmployeeTreeNode[] {
     new EmployeeTreeNode("Dirk Newman", 70000,f.parse("2007-08-21")),
     new EmployeeTreeNode("Emerson Milton",72000,f.parse("2009-05-07")),
     new EmployeeTreeNode("Gail Horton", 680000,f.parse("2008-05-01")), }),
    new Folder("S/W Engineer",new EmployeeTreeNode[] {
     new EmployeeTreeNode("Claudio Engle", 50000,f.parse("2007-02-01")),
     new EmployeeTreeNode("Buster misjenou",52000,f.parse("2009-06-10")),
     new EmployeeTreeNode("Bell Snedden", 50000,f.parse("2008-12-01")),
     new EmployeeTreeNode("Benito Meeks", 55000,f.parse("2006-05-01")), }), }),
 
   new Folder("Marketing", new Folder[] { 
    new Folder("Executive",new EmployeeTreeNode[] {
     new EmployeeTreeNode("Candice Carson", 50000, f.parse("2007-08-21")),
     new EmployeeTreeNode("Mildred Starnes", 50000,f.parse("2008-05-01")),
     new EmployeeTreeNode("Claudio Engle", 50000, f.parse("2009-06-15")), }), }), 
  };

  Folder root = new Folder("root");
  for (int i = 0; i < folders.length; i++) {
   root.add((Folder) folders[i]);
  }

  return root;
  }
}
You data is now ready to create a simple Tree. Go to the onModuleLoad method of GxtBasicTree class. Remove all the auto generated code of this method. Now first create a root object named model of the Folder class from TestData.getTreeModel() method and create a TreeStore object,store from this model.
public static final ExampleIcons ICONS = GWT.create(ExampleIcons.class);
public void onModuleLoad() 
{
       Folder model = TestData.getTreeModel();  
     
       TreeStore<ModelData> store = new TreeStore<ModelData>();  
       store.add(model.getChildren(), true);  
 
Now create a TreePanel, tree from this store and set display name, width and style of the tree.
final TreePanel<ModelData> tree = new TreePanel<ModelData>(store);  
       tree.setDisplayProperty("name");  
       tree.setWidth(250);  
       tree.getStyle().setLeafIcon(ICONS.user_add());
The two button expand and collapse provide the expand and collapse functionality by simple calling the tree.expandAll() and tree.collapseAll() method.
ButtonBar buttonBar = new ButtonBar();  
       Button expand = new Button("Expand All"); 
       Button collapse = new Button("Collapse All"); 
       expand.addSelectionListener(new SelectionListener<ButtonEvent>() {  
       public void componentSelected(ButtonEvent ce) {  
           tree.expandAll();  
         }  
       });
       
       collapse.addSelectionListener(new SelectionListener<ButtonEvent>() {  
        public void componentSelected(ButtonEvent ce) {  
            tree.collapseAll();  
          }  
        });
       buttonBar.add(expand);
       buttonBar.add(collapse);
        
       RootPanel.get().add(buttonBar);
       RootPanel.get().add(tree);
       
 }


That's all. Run it and check the functionality of the simple tree. To view the live demo of this tutorial Click here.

32 comments:

Andrew from NZ November 27, 2009 at 3:16 PM  

Hi, nice tutorial. Note the 'new EmployeeTreeNode' references should just be 'new Employee' - at least that change worked for me.

Also, the 'GWT.create(ExampleIcons.class)' bit did not work. Does it need a particular import? When I commented that line and the 'tree.getStyle().setLeafIcon(ICONS.user_add());' line, it all worked.

Lots of thanks!

Unknown November 27, 2009 at 11:20 PM  

Thanks Andrew for pointing out the problem. I have changed the Employee class name to EmployeeTreeNode.
And the ExampleIcons is a ImageBundle class. you can make make your image bundle class yourself...

Andrew from NZ November 28, 2009 at 7:48 PM  

Hmmm, I haven't got to image bundles yet! I've only just started trying with ExtGWT.

The big problem I have now is getting server data into a tree. I've tried a bunch of tutorials but they never work. Even the ExtGWT examples are missing files.

I can create a tree from this tutorial using the datastore approach but I'd really like the data to be provided via RPC. I can get RPC to work (simple communication between client and server) but I cannot find any tutorial (that works) that shows the data proxy/binding piece (really simply).

Could you do a new tutorial that is exactly like this but the data is provided by the server via RPC?

Thanks for listening!!!

Unknown November 28, 2009 at 9:19 PM  

In our project we are using ejb as the business tier and Ext GWT as the presentation tier. I have a plan to write a tutorial about communicating GWT rpc with ejb session bean. Then i will write your demanded one. Just need some time to write those. So keep patience :) ...

Manish Gupta December 2, 2009 at 11:47 PM  

hi ratul, actualy I am truing to creating a tree in aborderlay out in west side And to want connetct each node with some grid (table ) please help me I am not able to connect the grid with tre node how the listener will work I am trying for long time as my best but unable to find solution please help me ASAp ....thanks in advance

Unknown December 3, 2009 at 12:42 AM  
This comment has been removed by the author.
Unknown December 3, 2009 at 12:44 AM  

You can use gxt MVC for event handling.

I assume you have TreePanel tree.
private TreePanel<ModelData> tree;

So you can register the event in this way..

SelectionService.get().addListener(new SourceSelectionChangedListener(tree.getSelectionModel()));
SelectionService.get().register(tree.getSelectionModel());

Unknown December 7, 2009 at 9:26 AM  

Thank you for a good step by step example.
But I have one single problem when I run that example using latest Ext GWT 2.1.0 SDK: when I click by mouse on three nodes they are not displayed with selection.
I tried to use previous Ext GWT 1.2.4 SDK, but this version does not have TreePanel class...
the same problem happens also with my another example with TreePanel usage...
Please help..
Thank you,
Evgeny

Unknown December 7, 2009 at 7:22 PM  

Hi Evgeny,
I used gxt-2.0.1 sdk for writing this tutorial. I have just downloaded the gxt-2.1.0 sdk. I will try with this sdk and inform your whether i am facing any problem or not. Thanks,
Ratul

Unknown December 11, 2009 at 2:18 AM  

@Evgeny: I am now working with gxt-2.1.0 and facing no problem. Rather some bugs are solved in this version. Please re-check your code.Thanks.

Unknown December 17, 2009 at 12:36 AM  

Thank you, that is working for me now!

Unknown April 6, 2010 at 4:20 AM  

Hello, thanks for the tutorial. I tried to follow it but I have some problems : it doesn't work for me. I have no error, it can compile, I can see the expand and collapse buttons but the tree doesn't show on my browser.
I don't know what to do, I'm new to GWT and I never managed to make ExtGXT work !
I have GWT 2.0.3 and ExtGWT 2.1.1
Can you think of something I did wrong ? Did I have to add something in the html file ? or the xml file ?
Thanks

Unknown April 6, 2010 at 6:08 AM  

I don't know why but I add 'tree.setHeight(250);' and now it works ! I don't see the images because i commented the lines 'GWT.create(ExampleIcons.class)' and 'tree.getStyle().setLeafIcon(ICONS.user_add());' but it's ok !

Unknown April 6, 2010 at 10:25 PM  

@Titange: Congratulation :-) It may happen for the layout u used.

If you want to see the image you have to create an Image Bundle class. In my example ExampleIcons is an image bundle class.

Anonymous April 22, 2010 at 7:13 AM  

Wow, I was searchig info about Cave Bears and I get here :) isn't it funny:)

Saravanan May 26, 2010 at 10:23 PM  

hi..i am new to GWT. i would liek to use this tree panel as a navigation path. like.i shall provide all the links..and clicking on the leaf node, it has to create event which will open the new screen as like...ext js examples. can anyone help me on this.

Unknown May 28, 2010 at 9:15 PM  

@Saravanan: You can use GXT MVC for your purpose. The GXT demo is built on this too.

Unknown January 5, 2011 at 9:52 PM  

Hi.
My requirement is to display context menu based on selection node.
But with right click node is not selecting how to add right click listener to tree and make it selected.

plz help me...
thanks in advance..

Unknown January 6, 2011 at 4:08 AM  

@mallikarjun: hop will this link help you.

Unknown April 26, 2011 at 1:49 PM  

This example does not appear to work when simple BaseTreeModels are used instead of the fancy wrapper classes (e.g., Folder). Child nodes do not display when the parent is expanded. Why is that?

Unknown April 26, 2011 at 2:41 PM  

Actually, the child node renders, but is hidden because the layout container is not auto-expanding to show it (presenting scroll arrows instead). How did you get the TreePanel to expand the height of the layout container?

Unknown April 26, 2011 at 7:57 PM  

@Arythmael: Try with flow layout. Css provided by gxt naturally supports auto expanding of the treepanel. if it is not working in your case try to override the css.

Gabriele June 15, 2011 at 7:22 AM  

Hi Shamas! Great tutorial, thanks. But i'have some trouble..eclipse does not recognize TreePanel.

What i can do? There is some import to do?

Thank you,

Gabriele.

Gabriele June 17, 2011 at 2:30 AM  

I resolved my problem updating the gxt library..now i have not errors compiling the code, but when i run the project with eclipse in the 'Development mode' tab appear a lot of time this error: " No source code is available for type com.extjs.gxt.ui.client.data.BaseTreeModel; did you forget to inherit a required module?". I read in the Web that i must to add GXT jar to launch configuration also. Do you know what can do my mistake?

Thanks, Gabriele.

Unknown June 18, 2011 at 12:07 AM  

@Gabriele : Sorry for beign late. you may forgot to inherit gxt package in your project.gwt.xml file. Add this line in the file

<inherits name='com.extjs.gxt.ui.GXT'/>
This blog can help you.

Gabriele June 20, 2011 at 9:34 AM  

Don't worry about the late :)..indeed your answer was very important for me..i follow your tip and now the project work..

Thanks again,

Gabriele

JaKida September 18, 2011 at 9:36 AM  

Nice Tutorial Ratul. Everything in your tutorial looks straight forward however one thing I dont understand is the purpose of the ID field for the folder class, is it needed? When does it get used?

Thanks again

Unknown September 18, 2011 at 11:54 PM  

@Jakida: You need the ID field if you want to do some operation based on this ID. Like getting a list of music under the selected folder.

Unknown June 25, 2012 at 8:43 PM  

i have a webservice create by asp.net. so how to call to grid to get data

Anonymous July 17, 2012 at 1:18 PM  

Hi, I tried this tutorial.
But in UI visible is onle 2 buttons: expand and collapse.

This is final TreePanel tree = new TreePanel(store) (when I debug) (null handle).
What it can be?
Thanks, Yura

Unknown December 9, 2013 at 3:56 AM  
This comment has been removed by the author.
Anonymous December 9, 2013 at 3:59 AM  


This was nice example,I have some other problem here.

I wrote below code,I could not set the panel to the right most side of the container,mu idea is I want control in moving the panel all the sides,like east ,west ,north and south.

public void onModuleLoad() {
Viewport viewport = new Viewport();
viewport.setLayout(new FlowLayout());
viewport.add(createContainer());
RootPanel.get().add(viewport);
}
private Widget createContainer() {
// TODO Auto-generated method stub
LayoutContainer container = new LayoutContainer();
container.setLayout(new BorderLayout());
ContentPanel panel=new ContentPanel(new FitLayout());
panel.setHeading("The Legend");
BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST, 250);
westData.setSplit(true);
westData.setCollapsible(true);
westData.setMargins(new Margins(0, 3, 0, 0));
container.add(panel,westData);
return container;
}

Can someone help?

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers