![]() |
||
![]() |
![]() Alden Hosting provides professional, efficient, and reliable business-class Web hosting services to small- and medium-sized businesses. |
|
|
JAVA, JSP, SERVLETS, TOMCAT, SERVLETS MANAGER, |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
![]() |
![]() |
![]() |
| Java look and feel | Windows look and feel | Mac OS look and feel |
As the preceding figures show, a tree conventionally displays an icon and some text for each node. You can customize these, as we will show shortly.
A tree typically also performs some look-and-feel-specific
painting to indicate relationships between nodes.
You can customize this painting in a limited way.
First, you can use
tree.setRootVisible(true)
to show the root node or
tree.setRootVisible(false)
to hide it.
Second, you can use
tree.setShowsRootHandles(true)
to request that a tree's top-level nodes —
the root node (if it is visible) or its children (if not) —
have handles that let them be expanded or collapsed.
If you are using the Java look and feel,
you can customize whether lines are drawn
to show relationships between tree nodes.
By default, the Java look and feel
draws angled lines between nodes.
By setting the JTree.lineStyle
client property of a tree,
you can specify
a different convention.
For example,
to request that the Java look and feel use
only horizontal lines to group nodes,
use the following code:
tree.putClientProperty("JTree.lineStyle", "Horizontal");
To specify that the Java look and feel should draw no lines, use this code:
tree.putClientProperty("JTree.lineStyle", "None");
The following snapshots show the results
of setting the JTree.lineStyle property,
when using the Java look and feel.
![]() |
![]() |
![]() |
"Angled" (default)
|
"Horizontal"
|
"None"
|
No matter what the look and feel, the default icon displayed by a node is determined by whether the node is a leaf and, if not, whether it is expanded. For example, in the Windows and Motif look and feel implementations, the default icon for each leaf node is a dot; in the Java look and feel, the default leaf icon is a paper-like symbol. In all the look-and-feel implementations we have shown, branch nodes are marked with folder-like symbols. Some look and feels might have different icons for expanded branches versus collapsed branches.
You can easily change the default icon used for leaf,
expanded branch, or collapsed branch nodes.
To do so, you first create an instance of
DefaultTreeCellRenderer. You could always create your own TreeCellRenderer implementation from scratch, reusing whatever components you like.
Next, specify the icons to use by invoking one or more of the
following methods on the renderer:
setLeafIcon (for leaf nodes),
setOpenIcon (for expanded branch nodes),
setClosedIcon (for collapsed branch nodes).
If you want the tree to display no icon
for a type of node,
then specify null for the icon.
Once you have set up the icons,
use the tree's setCellRenderer method
to specify that the DefaultTreeCellRenderer
paint its nodes.
Here is an example,
taken from
TreeIconDemo.java:
ImageIcon leafIcon = createImageIcon("images/middle.gif");
if (leafIcon != null) {
DefaultTreeCellRenderer renderer =
new DefaultTreeCellRenderer();
renderer.setLeafIcon(leafIcon);
tree.setCellRenderer(renderer);
}
Here is the screenshot of TreeIconDemo:
Try this::
- Click the Launch button to run the TreeIconDemo using Java™ Web Start (download JDK 6). Alternatively, to compile and run the example yourself, consult the example index.
![]()
If you want finer control over the node icons
or you want to provide tool tips,
you can do so by creating a
subclass of DefaultTreeCellRenderer
and overriding the getTreeCellRendererComponent method.
Because DefaultTreeCellRenderer
is a subclass of JLabel,
you can use any JLabel method —
such as setIcon —
to customize the DefaultTreeCellRenderer.
The following code, from
TreeIconDemo2.java, creates a cell renderer
that varies the leaf icon
depending on whether the word "Tutorial"
is in the node's text data.
The renderer also specifies tool-tip text,
as the bold lines show.
Try this::
- Click the Launch button to run the TreeIconDemo2 using Java™ Web Start (download JDK 6). Alternatively, to compile and run the example yourself, consult the example index.
![]()
//...where the tree is initialized:
//Enable tool tips.
ToolTipManager.sharedInstance().registerComponent(tree);
ImageIcon tutorialIcon = createImageIcon("images/middle.gif");
if (tutorialIcon != null) {
tree.setCellRenderer(new MyRenderer(tutorialIcon));
}
...
class MyRenderer extends DefaultTreeCellRenderer {
Icon tutorialIcon;
public MyRenderer(Icon icon) {
tutorialIcon = icon;
}
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);
if (leaf && isTutorialBook(value)) {
setIcon(tutorialIcon);
setToolTipText("This book is in the Tutorial series.");
} else {
setToolTipText(null); //no tool tip
}
return this;
}
protected boolean isTutorialBook(Object value) {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode)value;
BookInfo nodeInfo =
(BookInfo)(node.getUserObject());
String title = nodeInfo.bookName;
if (title.indexOf("Tutorial") >= 0) {
return true;
}
return false;
}
}
Here is the result:
You might be wondering how a cell renderer works.
When a tree paints each node,
neither the JTree
nor its look-and-feel-specific implementation actually
contains the code that paints the node.
Instead, the tree uses the cell renderer's painting code
to paint the node.
For example, to paint
a leaf node that has the string "The Java Programming Language",
the tree asks its cell renderer
to return a component
that can paint a leaf node with that string.
If the cell renderer is a DefaultTreeCellRenderer,
then it returns a label that paints the default leaf icon
followed by the string.
A cell renderer only paints; it cannot handle events. If you want to add event handling to a tree, you need to register your handler on either the tree or, if the handling occurs only when a node is selected, the tree's cell editor. For information about cell editors, see Concepts: Editors and Renderers. That section discusses table cell editors and renderers, which are similar to tree cell editors and renderers.
The following figure shows an application called DynamicTreeDemo that lets you add nodes to and remove nodes from a visible tree. You can also edit the text in each node.The application is based on an example provided by tutorial reader Richard Stanford.
Here is the code that initializes the tree:
Try this::
- Click the Launch button to run the DynamicTreeDemo using Java™ Web Start (download JDK 6). Alternatively, to compile and run the example yourself, consult the example index.
![]()
By explicitly creating the tree's model, the code guarantees that the tree's model is an instance ofrootNode = 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);DefaultTreeModel. That way, we know all the methods that the tree model supports. For example, we know that we can invoke the model'sinsertNodeIntomethod, even though that method is not required by theTreeModelinterface.To make the text in the tree's nodes editable, we invoke
setEditable(true)on the tree. When the user has finished editing a node, the model generates a tree model event that tells any listeners — including theJTree— that tree nodes have changed. Note that althoughDefaultMutableTreeNodehas methods for changing a node's content, changes should go through theDefaultTreeModelcover methods. Otherwise, the tree model events would not be generated, and listeners such as the tree would not know about the updates.To be notified of node changes, we can implement a
TreeModelListener. Here is an example of a tree model listener that detects when the user has typed in a new name for a tree node:class MyTreeModelListener implements TreeModelListener { public void treeNodesChanged(TreeModelEvent e) { DefaultMutableTreeNode node; node = (DefaultMutableTreeNode) (e.getTreePath().getLastPathComponent()); /* * If the event lists children, then the changed * node is the child of the node we have already * gotten. Otherwise, the changed node and the * specified node are the same. */ try { int index = e.getChildIndices()[0]; node = (DefaultMutableTreeNode) (node.getChildAt(index)); } catch (NullPointerException exc) {} System.out.println("The user has finished editing the node."); System.out.println("New value: " + node.getUserObject()); } public void treeNodesInserted(TreeModelEvent e) { } public void treeNodesRemoved(TreeModelEvent e) { } public void treeStructureChanged(TreeModelEvent e) { } }Here is the code that the Add button's event handler uses to add a new node to the tree:
The code creates a node, inserts it into the tree model, and then, if appropriate, requests that the nodes above it be expanded and the tree scrolled so that the new node is visible. To insert the node into the model, the code uses thetreePanel.addObject("New Node " + newNodeSuffix++); ... public DefaultMutableTreeNode addObject(Object child) { DefaultMutableTreeNode parentNode = null; TreePath parentPath = tree.getSelectionPath(); if (parentPath == null) { //There is no selection. Default to the root node. parentNode = rootNode; } else { parentNode = (DefaultMutableTreeNode) (parentPath.getLastPathComponent()); } return addObject(parentNode, child, true); } ... public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible) { DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child); ... treeModel.insertNodeInto(childNode, parent, parent.getChildCount()); //Make sure the user can see the lovely new node. if (shouldBeVisible) { tree.scrollPathToVisible(new TreePath(childNode.getPath())); } return childNode; }insertNodeIntomethod provided by theDefaultTreeModelclass.
IfDefaultTreeModeldoes not suit your needs, then you will need to write a custom data model. Your data model must implement theTreeModelinterface.TreeModelspecifies methods for getting a particular node of the tree, getting the number of children of a particular node, determining whether a node is a leaf, notifying the model of a change in the tree, and adding and removing tree model listeners.Interestingly, the
TreeModelinterface accepts any kind of object as a tree node. It does not require that nodes be represented byDefaultMutableTreeNodeobjects, or even that nodes implement theTreeNodeinterface. Thus, if theTreeNodeinterface is not suitable for your tree model, feel free to devise your own representation for tree nodes. For example, if you have a pre-existing hierarchical data structure, you do not need to duplicate it or force it into theTreeNodemold. You just need to implement your tree model so that it uses the information in the existing data structure.The following figure shows an application called GenealogyExample that displays the descendants or ancestors of a particular person. (Thanks to tutorial reader Olivier Berlanger for providing this example.)
Try this::
- Click the Launch button to run the Genealogy Example using Java™ Web Start (download JDK 6). Alternatively, to compile and run the example yourself, consult the example index.
![]()
You can find the custom tree model implementation in
GenealogyModel.java. Because the model is implemented as anObjectsubclass instead of, say, a subclass ofDefaultTreeModel, it must implement theTreeModelinterface directly. This requires implementing methods for getting information about nodes, such as which is the root and what are the children of a particular node. In the case ofGenealogyModel, each node is represented by an object of typePerson, a custom class that does not implementTreeNode.A tree model must also implement methods for adding and removing tree model listeners, and must fire
TreeModelEvents to those listeners when the tree's structure or data changes. For example, when the user instructs GenealogyExample to switch from showing ancestors to showing descendants, the tree model makes the change and then fires an event to inform its listeners (such as the tree component).
Lazy loading is a characteristic of an application when the actual loading and instantiation of a class is delayed until the point just before the instance is actually used.Do we gain anything by loading them lazily? Yes, this would definitely add to the performance of an application. By lazily loading, you can dedicate the memory resources to load and instantiate an object only when it is actually used. You can also speed up the initial loading time of an application.
One of the ways you can lazily load children of a Tree is by utilizing the TreeWillExpandListener interface. For example, you can declare and load root, grandparent and parent of a Tree along with the application as shown in the following code:
Let us declare the root, grandparent and parent as shown below:
You can load above declared nodes to the tree as shown in the following code:class DemoArea extends JScrollPane implements TreeWillExpandListener { ....... ....... private TreeNode createNodes() { DefaultMutableTreeNode root; DefaultMutableTreeNode grandparent; DefaultMutableTreeNode parent; root = new DefaultMutableTreeNode("San Francisco"); grandparent = new DefaultMutableTreeNode("Potrero Hill"); root.add(grandparent); parent = new DefaultMutableTreeNode("Restaurants"); grandparent.add(parent); dummyParent = parent; return root; }TreeNode rootNode = createNodes(); tree = new JTree(rootNode); tree.addTreeExpansionListener(this); tree.addTreeWillExpandListener(this); ....... ....... setViewportView(tree);Now, you can load children lazily to the application whenever the parent node
Restaurantsis visible in the application. To do this, let us declare two children in a separate method and call that method as shown in the following code:private void LoadLazyChildren(){ DefaultMutableTreeNode child; child = new DefaultMutableTreeNode("Thai Barbeque"); dummyParent.add(child); child = new DefaultMutableTreeNode("Goat Hill Pizza"); dummyParent.add(child); textArea.append(" Thai Barbeque and Goat Hill Pizza are loaded lazily"); } ....... ....... public void treeWillExpand(TreeExpansionEvent e) throws ExpandVetoException { saySomething("You are about to expand node ", e); int n = JOptionPane.showOptionDialog( this, willExpandText, willExpandTitle, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, willExpandOptions, willExpandOptions[1]); LoadLazyChildren(); }See How to Write a Tree-Will-Expand Listener for a description of Tree-Will-Expand listeners.
The Tree API
The tree API is quite extensive. The following tables list just a bit of the API, concentrating on the following categories:
- Tree-Related Classes and Interfaces
- Creating and Setting Up a Tree
- Implementing Selection
- Showing and Hiding Nodes
For more information about the tree API, see the API documentation for
JTreeand for the various classes and interfaces in the tree package. Also refer to The JComponent Class for information on the APIJTreeinherits from its superclass.
Tree-Related Classes and Interfaces Class or Interface Purpose JTree The component that presents the tree to the user. TreePath Represents a path to a node. TreeNode
MutableTreeNode
DefaultMutableTreeNodeThe interfaces that the default tree model expects its tree nodes to implement, and the implementation used by the default tree model. TreeModel
DefaultTreeModelRespectively, the interface that a tree model must implement and the usual implementation used. TreeCellRenderer
DefaultTreeCellRendererRespectively, the interface that a tree cell renderer must implement and the usual implementation used. TreeCellEditor
DefaultTreeCellEditorRespectively, the interface that a tree cell editor must implement and the usual implementation used. TreeSelectionModel
DefaultTreeSelectionModelRespectively, the interface that the tree's selection model must implement and the usual implementation used. TreeSelectionListener
TreeSelectionEventThe interface and event type used for detecting tree selection changes. For more information, see Getting Started. TreeModelListener
TreeModelEventThe interface and event type used for detecting tree model changes. For more information, see How to Write a Tree Model Listener. TreeExpansionListener
TreeWillExpandListener
TreeExpansionEventThe interfaces and event type used for detecting tree expansion and collapse. For more information, see How to Write a Tree Expansion Listener and How to Write a Tree-Will-Expand Listener. ExpandVetoException An exception that a TreeWillExpandListenercan throw to indicate that the impending expansion/collapse should not happen. For more information, see How to Write a Tree-Will-Expand Listener.
Creating and Setting Up a Tree Constructor or Method Purpose JTree(TreeNode)
JTree(TreeNode, boolean)
JTree(TreeModel)
JTree()
JTree(Hashtable)
JTree(Object[])
JTree(Vector)Create a tree. The TreeNodeargument specifies the root node, to be managed by the default tree model. TheTreeModelargument specifies the model that provides the data to the table. The no-argument version of this constructor is for use in builders; it creates a tree that contains some sample data. If you specify aHashtable, array of objects, ofVectoras an argument, then the argument is treated as a list of nodes under the root node (which is not displayed), and a model and tree nodes are constructed accordingly.The
booleanargument, if present, specifies how the tree should determine whether a node should be displayed as a leaf. If the argument is false (the default), any node without children is diaplayed as a leaf. If the argument is true, a node is a leaf only if itsgetAllowsChildrenmethod returns false.void setCellRenderer(TreeCellRenderer) Set the renderer that draws each node. void setEditable(boolean)
void setCellEditor(TreeCellEditor)The first method sets whether the user can edit tree nodes. By default, tree nodes are not editable. The second sets which customized editor to use. void setRootVisible(boolean) Set whether the tree shows the root node. The default value is false if the tree is created using one of the constructors that takes a data structure, and true otherwise. void setShowsRootHandles(boolean) Set whether the tree shows handles for its leftmost nodes, letting you expand and collapse the nodes. The default is false. If the tree does not show the root node, then you should invoke setShowsRootHandles(true).void setDragEnabled(boolean)
boolean getDragEnabled()Set or get the dragEnabledproperty, which must be true to enable drag handling on this component. The default value is false. See Drag and Drop for more details.
Implementing Selection Method Purpose void addTreeSelectionListener(TreeSelectionListener) Register a listener to detect when the a node is selected or deselected. void setSelectionModel(TreeSelectionModel)
TreeSelectionModel getSelectionModel()Set or get the model used to control node selections. You can turn off node selection completely using setSelectionModel(null).void setSelectionMode(int)
int getSelectionMode()
(inTreeSelectionModel)Set or get the selection mode. The value can be CONTIGUOUS_TREE_SELECTION,DISCONTIGUOUS_TREE_SELECTION, orSINGLE_TREE_SELECTION(all defined inTreeSelectionModel).Object getLastSelectedPathComponent() Get the object representing the currently selected node. This is equivalent to invoking getLastPathComponenton the value returned bytree.getSelectionPath().void setSelectionPath(TreePath)
TreePath getSelectionPath()Set or get the path to the currently selected node. void setSelectionPaths(TreePath[])
TreePath[] getSelectionPaths()Set or get the paths to the currently selected nodes. void setSelectionPath(TreePath)
TreePath getSelectionPath()Set or get the path to the currently selected node.
Showing and Hiding Nodes Method Purpose void addTreeExpansionListener(TreeExpansionListener)
void addTreeWillExpandListener(TreeWillExpandListener)Register a listener to detect when the tree nodes have expanded or collapsed, or will be expanded or collapsed, respectively. To veto an impending expansion or collapse, a TreeWillExpandListenercan throw aExpandVetoException.void expandPath(TreePath)
void collapsePath(TreePath)Expand or collapse the specified tree path. void scrollPathToVisible(TreePath) Ensure that the node specified by the path is visible — that the path leading up to it is expanded and the node is in the scroll pane's viewing area. void makeVisible(TreePath) Ensure that the node specified by the path is viewable — that the path leading up to it is expanded. The node might not end up within the viewing area. void setScrollsOnExpand(boolean)
boolean getScrollsOnExpand()Set or get whether the tree attempts to scroll to show previous hidden nodes. The default value is true. void setToggleClickCount(int)
int getToggleClickCount()Set or get the number of mouse clicks before a node will expand or close. The default is two. TreePath getNextMatch(String, int, Position.Bias) Return the TreePathto the next tree element that begins with the specific prefix.Examples that Use Trees
This table lists examples that useJTreeand where those examples are described.
Example Where Described Notes TreeDemo Creating a Tree, Responding to Node Selection, Customizing a Tree's Display Creates a tree that responds to user selections. It also has code for customizing the line style for the Java look and feel. TreeIconDemo Customizing a Tree's Display Adds a custom leaf icon to TreeDemo. TreeIconDemo2 Customizing a Tree's Display Customizes certain leaf icons and also provides tool tips for certain tree nodes. DynamicTreeDemo Dynamically Changing a Tree Illustrates adding and removing nodes from a tree. Also allows editing of node text. GenealogyExample Creating a Data Model Implements a custom tree model and custom node type. TreeExpandEventDemo How to Write a Tree Expansion Listener Shows how to detect node expansions and collapses. TreeExpandEventDemo2 How to Write a Tree-Will-Expand Listener Shows how to veto node expansions. TreeTable, TreeTable II, Editable JTreeTable Creating TreeTables in Swing, Creating TreeTables: Part 2, Editable JTreeTable Examples in The Swing Connection that combine a tree and table to show detailed information about a hierarchy such as a file system. The tree is a renderer for the table.
Alden Hosting offers private JVM (Java Virtual Machine), Java Server Pages (JSP), Servlets, and Servlets Manager with our Web Hosting Plans WEB 4 PLAN and WEB 5 PLAN , WEB 6 PLAN .
At Alden Hosting we eat and breathe Java! We are the industry leader in providing affordable, quality and efficient Java web hosting in the shared hosting marketplace. All our sites run on our Java hosing platform configured for optimum performance using Java 1.6, Tomcat 6, MySQL 5, Apache 2.2 and web application frameworks such as Struts, Hibernate, Cocoon, Ant, etc.
We offer only one type of Java hosting - Private Tomcat. Hosting accounts on the Private Tomcat environment get their very own Tomcat server. You can start and re-start your entire Tomcat server yourself.
![]() |
|
http://alden-servlet-Hosting.com
JSP at alden-servlet-Hosting.com
Servlets at alden-servlet-Hosting.com
Servlet at alden-servlet-Hosting.com
Tomcat at alden-servlet-Hosting.com
MySQL at alden-servlet-Hosting.com
Java at alden-servlet-Hosting.com
sFTP at alden-servlet-Hosting.com
http://alden-tomcat-Hosting.com
JSP at alden-tomcat-Hosting.com
Servlets at alden-tomcat-Hosting.com
Servlet at alden-tomcat-Hosting.com
Tomcat at alden-tomcat-Hosting.com
MySQL at alden-tomcat-Hosting.com
Java at alden-tomcat-Hosting.com
sFTP at alden-tomcat-Hosting.com
http://alden-sftp-Hosting.com
JSP at alden-sftp-Hosting.com
Servlets at alden-sftp-Hosting.com
Servlet at alden-sftp-Hosting.com
Tomcat at alden-sftp-Hosting.com
MySQL at alden-sftp-Hosting.com
Java at alden-sftp-Hosting.com
sFTP at alden-sftp-Hosting.com
http://alden-jsp-Hosting.com
JSP at alden-jsp-Hosting.com
Servlets at alden-jsp-Hosting.com
Servlet at alden-jsp-Hosting.com
Tomcat at alden-jsp-Hosting.com
MySQL at alden-jsp-Hosting.com
Java at alden-jsp-Hosting.com
sFTP at alden-jsp-Hosting.com
http://alden-java-Hosting.com
JSp at alden-java-Hosting.com
Servlets at alden-java-Hosting.com
Servlet at alden-java-Hosting.com
Tomcat at alden-java-Hosting.com
MySQL at alden-java-Hosting.com
Java at alden-java-Hosting.com
sFTP at alden-java-Hosting.com
JSP
Servlets
Tomcat
mysql
Java
JSP
Servlets
Tomcat
mysql
Java
JSP
Servlets
Tomcat
mysql
Java
JSP
Servlets
Tomcat
mysql
Java
JSP at JSP.aldenWEBhosting.com
Servlets at servlets.aldenWEBhosting.com
Tomcat at Tomcat.aldenWEBhosting.com
mysql at mysql.aldenWEBhosting.com
Java at Java.aldenWEBhosting.com
Web Hosts Portal
Web Links
Web Links
Web Hosting
JSP Solutions Web Links
JSP Solutions Web Hosting
Servlets Solutions Web Links
Servlets Solutions Web Hosting
Web Links
Web Links
.
.
.
.
.
.
.
.
.
.
jsp hosting
servlets hosting
web hosting
web sites designed
cheap web hosting
web site hosting
myspace web hosting