JTree node parsing
Hi
I have a JTree where the which has a list of subnodes( please note that i m adding new functionality to existing java application )
the new functionality must on user click on a node , must do list all files under that node and process those files
i have parsed the node as follows , is this a elegant way ? is there any other better way to do it
levels of parsing is fixed to 4 levels ( so 4 time for loops )
public void valueChanged(TreeSelectionEvent e) {
NavigatorTreeNode node= null;
if (obj instanceof NavigatorTreeNode) {
node = (NavigatorTreeNode)obj;
if (node == null) return;
String path = node.getFileName();
boolean isLeaf, isRoot;
isLeaf = node.isLeaf();
isRoot = node.isRoot();
if(!isLeaf){
for(int i = 0 ; i < node.getChildCount(); i++){
System.out.println(node.getChildAt(i));
for(int j = 0 ; j < node.getChildAt(i).getChildCount(); j++){
System.out.println(" "+node.getChildAt(i).getChildAt(j));
for(int k = 0 ; k < node.getChildAt(i).getChildAt(j).getChildCount(); k++){
System.out.println(" "+node.getChildAt(i).getChildAt(j).getChildAt(k));
for(int l = 0 ; l < node.getChildAt(i).getChildAt(j).getChildAt(k).getChildCount(); l++){
System.out.println(" "+node.getChildAt(i).getChildAt(j).getChildAt(k).getChildAt(l));
//.......... furthur code ............
} // End of valueChanged
Depending on how you define 'elegance', you might want to have a look at recursion?
* I have not tested this code, so there's most likely a little flaw here and there.
* However, it might give you an idea as to how you can make your code a little
* more elegant?
public void valueChanged(TreeSelectionEvent e) {
if (e.getPath().getLastPathComponent() instanceof NavigatorTreeNode) {
printNode((NavigatorTreeNode) e.getPath().getLastPathComponent(), 0);
private void printNode(NavigatorTreeNode n, int l) {
if (n == null) {
return;
String inset = "-";
for (int i = 0; i < l; i++) {
inset += "-";
System.out.println(inset + " " + n.toString());
for (int i = 0; i < n.getChildCount(); i++) {
printNode(n.getChild(i), l + 1);
}
Similar Messages
-
Parse and display xml doc when click on JTree node?
Ok so here is the code that I have now. You will have to make alot of html files to run the program, but they can be empty for now. What you can do is just put the same exact html file to be displayed in each node element. for example.
DefaultMutableTreeNode n1_node1_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));could be changed to
DefaultMutableTreeNode n1_node1_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Device", "status.html"));And just keep adding the status.html page to each one of the nodes.
anyway.
For now when I click on the node, the html file is displayed in the JScrollPane rPane = new JScrollPane(htmlPane); and the htmlPane is a JEditorPane
what I need it to do.
When I click on the JTree node. I would like to go out to an xml file, parse the information in it, and display it to the pane.
I will need to later, be able to add, edit, or delete information on the xml through the pane later.
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.JTree;
import javax.swing.JPanel;
import javax.accessibility.*;
import javax.swing.UIManager;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.ImageIcon;
import java.net.URL;
import java.io.IOException;
import java.awt.Dimension;
* @author orozcom
public class Example extends JFrame implements TreeSelectionListener
private JEditorPane htmlPane;
private URL helpURL;
private static boolean DEBUG = false;
private JTree tree;
public Example()
super("Example");
setSize(1200,900);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JMenuBar jmb = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
System.exit(0);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(new JSeparator());
fileMenu.add(exitItem);
jmb.add(fileMenu);
setJMenuBar(jmb);
// **************** start JTree ******************//
JPanel lPane =new JPanel();
lPane.setLayout(new BorderLayout());
DefaultMutableTreeNode top = new DefaultMutableTreeNode(new ModuleInfo("Devices","splashScreen.html"));
DefaultMutableTreeNode branch1 =
new DefaultMutableTreeNode(new ModuleInfo("Module 1", "module1.html"));
DefaultMutableTreeNode branch2 =
new DefaultMutableTreeNode(new ModuleInfo("Module 2", "module2.html"));
//DefaultMutableTreeNode branch3 =
//new DefaultMutableTreeNode(new ModuleInfo("Module 3", "module3.html"));
//adding to the topmost node
top.add(branch1);
top.add(branch2);
//top.add(branch3);
* BRANCH 1 *
//adding to the First branch
DefaultMutableTreeNode node1_b1
=new DefaultMutableTreeNode(new ModuleInfo("Status", "status.html"));
//branch1.add(node1_b1);
DefaultMutableTreeNode n1_node1_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));
DefaultMutableTreeNode n2_node1_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Network", "network.html"));
DefaultMutableTreeNode n3_node1_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Chassis", "chassis.html"));
DefaultMutableTreeNode n4_node1_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Resources", "resources.html"));
node1_b1.add(n1_node1_b1);
node1_b1.add(n2_node1_b1);
node1_b1.add(n3_node1_b1);
node1_b1.add(n4_node1_b1);
DefaultMutableTreeNode node2_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Project Editor", "projedit.html"));
DefaultMutableTreeNode node3_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Project Manager", "projmngt.html"));
DefaultMutableTreeNode node4_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Administration", "administration.html"));
DefaultMutableTreeNode n1_node4_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));
DefaultMutableTreeNode n2_node4_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Network", "network.html"));
DefaultMutableTreeNode n3_node4_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Users", "users.html"));
node4_b1.add(n1_node4_b1);
node4_b1.add(n2_node4_b1);
node4_b1.add(n3_node4_b1);
DefaultMutableTreeNode node5_b1 =
new DefaultMutableTreeNode(new ModuleInfo("Logging", "logging.html"));
branch1.add(node1_b1);
branch1.add(node2_b1);
branch1.add(node3_b1);
branch1.add(node4_b1);
branch1.add(node5_b1);
* BRANCH 2 *
//adding to the Second branch
DefaultMutableTreeNode node1_b2 =
new DefaultMutableTreeNode(new ModuleInfo("Status", "status.html"));
DefaultMutableTreeNode n1_node1_b2 =
new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));
DefaultMutableTreeNode n2_node1_b2 =
new DefaultMutableTreeNode(new ModuleInfo("Network", "network.html"));
DefaultMutableTreeNode n3_node1_b2 =
new DefaultMutableTreeNode(new ModuleInfo("Chassis", "chassis.html"));
DefaultMutableTreeNode n4_node1_b2 =
new DefaultMutableTreeNode(new ModuleInfo("Resources", "resources.html"));
node1_b2.add(n1_node1_b2);
node1_b2.add(n2_node1_b2);
node1_b2.add(n3_node1_b2);
node1_b2.add(n4_node1_b2);
DefaultMutableTreeNode node2_b2=
new DefaultMutableTreeNode(new ModuleInfo("Project Editor", "projedit.html"));
DefaultMutableTreeNode node3_b2=
new DefaultMutableTreeNode(new ModuleInfo("Project Manager", "projmngt.html"));
DefaultMutableTreeNode node4_b2=
new DefaultMutableTreeNode(new ModuleInfo("Administration", "administration.html"));
DefaultMutableTreeNode n1_node4_b2=
new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));
DefaultMutableTreeNode n2_node4_b2=
new DefaultMutableTreeNode(new ModuleInfo("Network", "network.html"));
DefaultMutableTreeNode n3_node4_b2=
new DefaultMutableTreeNode(new ModuleInfo("Users", "users.html"));
node4_b2.add(n1_node4_b2);
node4_b2.add(n2_node4_b2);
node4_b2.add(n3_node4_b2);
DefaultMutableTreeNode node5_b2=
new DefaultMutableTreeNode(new ModuleInfo("Logging", "logging.html"));
branch2.add(node1_b2);
branch2.add(node2_b2);
branch2.add(node3_b2);
branch2.add(node4_b2);
branch2.add(node5_b2);
* BRANCH 3 *
//adding to the Third branch
DefaultMutableTreeNode node1_b3=new DefaultMutableTreeNode("Status");
DefaultMutableTreeNode n1_node1_b3=new DefaultMutableTreeNode("Device");
DefaultMutableTreeNode n2_node1_b3=new DefaultMutableTreeNode("Network");
DefaultMutableTreeNode n3_node1_b3=new DefaultMutableTreeNode("Chassis");
DefaultMutableTreeNode n4_node1_b3=new DefaultMutableTreeNode("Resources");
node1_b3.add(n1_node1_b3);
node1_b3.add(n2_node1_b3);
node1_b3.add(n3_node1_b3);
node1_b3.add(n4_node1_b3);
DefaultMutableTreeNode node2_b3=new DefaultMutableTreeNode("Project Editor");
DefaultMutableTreeNode node3_b3=new DefaultMutableTreeNode("Project Manager");
DefaultMutableTreeNode node4_b3=new DefaultMutableTreeNode("Administration");
DefaultMutableTreeNode n1_node4_b3=new DefaultMutableTreeNode("Device");
DefaultMutableTreeNode n2_node4_b3=new DefaultMutableTreeNode("Network");
DefaultMutableTreeNode n3_node4_b3=new DefaultMutableTreeNode("Users");
node4_b3.add(n1_node4_b3);
node4_b3.add(n2_node4_b3);
node4_b3.add(n3_node4_b3);
DefaultMutableTreeNode node5_b3=new DefaultMutableTreeNode("Logging");
branch3.add(node1_b3);
branch3.add(node2_b3);
branch3.add(node3_b3);
branch3.add(node4_b3);
branch3.add(node5_b3);
tree=new JTree(top,true);
//tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
//Set the icon for leaf nodes.
ImageIcon deviceIcon = createImageIcon("/device.gif");
if (deviceIcon != null)
DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
renderer.setLeafIcon(deviceIcon);
tree.setCellRenderer(renderer);
else
System.err.println("Leaf icon missing; using default.");
//Listen for when the selection changes.
tree.addTreeSelectionListener(this);
//Create the scroll pane and add the tree to it.
//JScrollPane treeView = new JScrollPane(tree);
tree.setToolTipText(" and ");
lPane.add(tree);
getContentPane().add(lPane);
// **************** end JTree ******************//
htmlPane = new JEditorPane();
htmlPane.setEditable(false);
initHelp();
JScrollPane rPane = new JScrollPane(htmlPane);
JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, lPane, rPane);
jsp.setDividerLocation(180);
getContentPane().add(jsp, BorderLayout.CENTER);
JPanel bPane = new JPanel();
JButton okButton = new JButton("Ok");
JButton applyButton = new JButton("Apply");
JButton clearButton = new JButton("Clear");
bPane.add(okButton);
bPane.add(applyButton);
bPane.add(clearButton);
getContentPane().add(bPane, BorderLayout.SOUTH);
setVisible(true);
/** Required by TreeSelectionListener interface. */
public void valueChanged(TreeSelectionEvent e)
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (node == null) return;
Object nodeInfo = node.getUserObject();
if (node.isLeaf())
ModuleInfo module = (ModuleInfo)nodeInfo;
displayURL(module.moduleURL);
if (DEBUG)
System.out.print(module.moduleURL + ": \n ");
else
displayURL(helpURL);
if (DEBUG)
System.out.println(nodeInfo.toString());
private class ModuleInfo
public String deviceName;
public URL moduleURL;
public ModuleInfo(String device, String filename)
deviceName = device;
moduleURL = (URL)Example.class.getResource("/" + filename);
if (moduleURL == null)
System.err.println("Couldn't find file: "
+ filename);
public String toString()
return deviceName;
private void initHelp()
String s = "YFDemoHelp.html";
helpURL = Example.class.getResource("/" + s);
if (helpURL == null)
System.err.println("Couldn't open help file: " + s);
else if (DEBUG)
System.out.println("Help URL is " + helpURL);
displayURL(helpURL);
private void displayURL(URL url)
try
if (url != null)
htmlPane.setPage(url);
else
{ //null url
htmlPane.setText("File Not Found");
if (DEBUG)
System.out.println("Attempted to display a null URL.");
catch (IOException e)
System.err.println("Attempted to read a bad URL: " + url);
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path)
java.net.URL imgURL = Example.class.getResource(path);
if (imgURL != null)
return new ImageIcon(imgURL);
else
System.err.println("Couldn't find file: " + path);
return null;
public static void main(String args[])
new Example();
//new AssistiveExample();
}Thanks orozcomyes i can at the time of MIRO u can see both
go in SU01 for and user
in Parameters enter IVFIDISPLAY in Parameter ID and X in Paramater Value
thus for that user u will be able to c Invoice number and accounting number after saving MIRo
u will get message like
Invoice document 5105608893 was posted ( Accountng Documnt: 5100000000 )
hope this helps -
Xml in JTree: how to not collpase JTree node, when renaming XML Node.
Hi.
I'm writing some kind of XML editor. I want to view my XML document in JTree and make user able to edit contents of XML. I made my own TreeModel for JTree, which straight accesses XML DOM, produced by Xerces. Using DOM Events, I made good-looking JTree updates without collapsing JTree on inserting or removing XML nodes.
But there is a problem. I need to produce to user some method of renaming nodes. As I know, there is no way to rename node in w3c DOM. So I create new one with new name and copy all children and attributes to it. But in this way I got a new object of XML Node instead of renamed one. And I need to initiate rebuilding (treeStructureChanged event) of JTree structure. Renamed node collapses. If I use treeNodesChanged event (no rebuilding, just changes string view of JTree node), then when I try to operate with renamed node again, exception will be throwed.
Is there some way to rename nodes in my program without collpasing JTree?
I'am new to Java. Maybe there is a method in Xerces DOM implementation to rename nodes without recreating?
Thanks in advance.I assume that "rename" means to change the element name? Anyway your question seems to be "When I add a node to a JTree, how do I make sure it is expanded?" This is completely concerned with Swing, so it might have been better to post it in the Swing forum, but if it were me I would do this:
1. Copy the XML document into a JTree.
2. Allow the user to edit the document. Don't attempt to keep an XML document or DOM synchronized with the contents of the JTree.
3. On request of the user, copy the JTree back to a new XML document.
This way you can "rename" things to the user's heart's content without having the problem you described. -
PopupMenu on Jtree nodes Please [b]Help me][/b]
how can I set my JpopupMenu to work on Jtree nodes and not on the tree?
how can I set my JpopupMenu to work on Jtree nodes
and not on the tree?Could you elaborate? Are you asking that popup events are ignored if the mouse click is not actually on the rendered area of a node or are you asking something else? -
Now, I want to sort tree node by increasing.
for example there are three child node:
[20 -40][
10 - 20]
[30- 60].
they are added to JTree node by different order.but are shown in increasingorder.
like this:
[10 - 20]
[20 -40][
[30- 60].
how to control tree node.Implement the Comparable interface in t he userobject class and possibly the toString(0 as well.
Ex.
public class UserObject implements java.lang.Comparable{
public int compareTo(Object obj) throws ClassCastException
public String toString() -
Jtree node refuses to collapse upon clicking handle; makeVisible() was used
Hello,
While creating a new node and inserting as a leaf in the JTree, I use tree.makeVisible(newTreePath) to expand the new node and make visible. (Using expandPath() will not expand if a leaf was added).
However now the jtree node refuses to collapse upon clicking the node handle.
How do I get it to not insist on staying open - be able to collapse manually?
thanks,
AnilThis is the JNI forum. I don't believe your post fits.
then
can I correctly assume that any class that
"implements Cloneable" will handle making either a
"shallow" or "deep" ... or even "semi-shallow" clone,
respective to the class context .. right?
It probably does something. The implementor might not have implemented anything though. And you have no idea what they implemented.
No idea about your other question.
You might want to think carefully about why you are cloning though. -
Multiline text in a jtree node
i'm not able to add the multiline text in a jtree node. i've checked the data in both the cases before adding into the tree and after adding into the tree. itz getting the data in the proper format. but while displaying inside the tree itz taking into the single line.
kindly help me to get the data in a multi line format in the jtree.
thanks in advance.
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.text.*;
public class DynamicTreeDemo extends JPanel {
public static String transactionName=null;
String p1Name=null;
public static String duration=null;
public static final String NEWLINE = System.getProperty("line.separator");
static String[] arrCorrelatorId={"110","122","129","132","130","136","111","109","131","124","127",null};
static String[] arrParcorrelatorId={"108","110","122","129","122","130","108","108","109","121","121"};
static String[] arrtransactionName={"FINT3","FINT17","FINT20","FINT52","FINT21","FINT18","FINT4","FINT3"," FINT31","FINT19","FINT51"};
public static MutableTreeNode node;
public static DefaultTreeModel model;
public static TreePath path;
public static JTree tree;
static String[] nodeName={"FINT3_108","FINT17_110","FINT20_122","FINT52_129","FINT21_122","FINT18_110","FINT4_108","FINT3_108"," FINT31_109","FINT19_121","FINT51_121",null};
public DynamicTreeDemo(JFrame frame) {
final DynamicTree treePanel = new DynamicTree(transactionName);
populateTree(treePanel);
JTextField name = new JTextField(20);
setLayout(new BorderLayout());
treePanel.setPreferredSize(new Dimension(300, 150));
add(treePanel, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(10,50));
add(panel, BorderLayout.EAST);
public DefaultMutableTreeNode newObj(String parent){
DefaultMutableTreeNode pname= new DefaultMutableTreeNode(parent);
return pname;
public void populateTree(DynamicTree treePanel)
String p3;
DefaultMutableTreeNode p2,nNode, p1;
int ind=0, i=0,k=0, len=0, m=0;
boolean flag= false;
String desc;
while(nodeName[m]!=null)
p3 = nodeName[m];
ind = p3.indexOf("_");
p3 = p3.substring(0, ind);
desc=NEWLINE +"hi"+NEWLINE+"how r u";
if(arrParcorrelatorId[m].equals(arrParcorrelatorId[0]))
treePanel.addObject(null, p3,desc);
else{
int loopcount=0;
for(int j=0;nodeName[j]!=null;j++)
if(arrParcorrelatorId[m].equals(arrParcorrelatorId[j]))
for(int p=0;nodeName[p]!=null;p++)
if(arrCorrelatorId[p].equals(arrParcorrelatorId[j]))
p1=newObj(arrtransactionName[p]);
System.out.println("parent:"+p1);
System.out.println("child:"+p3);
treePanel.addObject(p1, p3,desc);
break;
break;
m++;
public static void showNodes(String corrId)
transactionName="FINT3";
public void DynamicDisplayNode(String corrId){
JFrame frame = new JFrame("DynamicTreeDemo");
showNodes(corrId);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(1,1));
contentPane.add(new DynamicTreeDemo(frame));
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
frame.pack();
frame.setVisible(true);
public static void main(String[] args)
JFrame frame1=null;
DynamicTreeDemo demo= new DynamicTreeDemo(frame1);
demo.DynamicDisplayNode("108");
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Enumeration;
import java.util.StringTokenizer;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.*;
public class DynamicTree extends JPanel {
protected DefaultMutableTreeNode rootNode;
protected DefaultTreeModel treeModel;
protected JTree tree;
protected DefaultTreeCellRenderer linksRenderer;
public static final String NEWLINE = System.getProperty("line.separator");
public DynamicTree(String appName) {
rootNode = new DefaultMutableTreeNode(appName);
treeModel = new DefaultTreeModel(rootNode);
tree = new JTree(treeModel);
tree.setEditable(false);
tree.setShowsRootHandles(true);
tree.setBackground(Color.white);
tree.setCellRenderer(new DefaultTreeCellRenderer()
public Component getTreeCellRendererComponent(JTree pTree,
Object pValue, boolean pIsSelected, boolean pIsExpanded,
boolean pIsLeaf, int pRow, boolean pHasFocus)
DefaultMutableTreeNode node = (DefaultMutableTreeNode)pValue;
JLabel lbl = (JLabel)super.getTreeCellRendererComponent(pTree, pValue, pIsSelected,pIsExpanded, pIsLeaf, pRow, pHasFocus);
lbl.setBorder(new LineBorder(Color.RED,1));
/* Component c = super.getTreeCellRendererComponent(pTree, pValue, pIsSelected,
pIsExpanded, pIsLeaf, pRow, pHasFocus);
if (node.isRoot())
c.setForeground(Color.red);
else if (node.getChildCount() > 0)
c.setForeground(Color.blue);
else if (pIsLeaf)
c.setForeground(Color.black);//new Color(0x736AFF));*/
setBackgroundNonSelectionColor(Color.white);
JPanel p = new JPanel();
p.setBackground(tree.getBackground());
Dimension d = lbl.getPreferredSize();
p.setPreferredSize(new Dimension(d.width, d.height));
p.add(lbl);
tree.setRowHeight(30);
return (p);
JScrollPane scrollPane = new JScrollPane(tree);
setLayout(new GridLayout(1,0));
add(scrollPane);
public void addObject(DefaultMutableTreeNode parent,Object child,String desc)
child=child+desc;
//System.out.println("child"+child);
DefaultMutableTreeNode parent1;
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(child);
if (parent == null)
parent = rootNode;
else
String parentName = (String)parent.getUserObject();
String tok;
Enumeration e=null;
e=(Enumeration) rootNode.breadthFirstEnumeration();
int breakloop=0;
parent = rootNode.getLastLeaf();
while (e.hasMoreElements() ) {
if(parent!= null)
//System.out.println("parent.toString():"+parent.toString());
tok=parent.toString();
StringTokenizer st = new StringTokenizer(tok);
parent1=newObj(st.nextToken());
if(parent1.getUserObject().equals(parentName))
breakloop=1;
break;
parent= parent.getPreviousNode();
if(breakloop==0)
parent = rootNode.getLastLeaf();
System.out.println("parent.toString():"+parent.toString());
System.out.println("childNode"+childNode.toString());
parent.add(childNode);
public DefaultMutableTreeNode newObj(String parent){
DefaultMutableTreeNode pname= new DefaultMutableTreeNode(parent);
return pname;
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 treeNodesRemoved(TreeModelEvent e) {
public void treeStructureChanged(TreeModelEvent e) {
}Here is a simple example.
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class MultiLineTreeDemo extends JFrame {
private JTree tree;
public static void main( String[] args ) throws Exception {
SwingUtilities.invokeLater( new Runnable() {
public void run() { new MultiLineTreeDemo(); }
public MultiLineTreeDemo() {
super( "MultiLineTreeDemo" );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
DefaultMutableTreeNode root = new DefaultMutableTreeNode( "<html>This is<p>the root node.</html>" );
DefaultMutableTreeNode node = new DefaultMutableTreeNode( "<html>This is<p>a child node.<html>" );
root.add( node );
tree = new JTree( root );
setLayout( new BorderLayout() );
JScrollPane scrollPane = new JScrollPane( tree );
add( scrollPane, BorderLayout.CENTER );
setSize( 200, 200 );
setVisible( true );
} -
Set different color for one JTree node
hello,
I managed to find how to set a color for Jtree nodes but the problem is that with my method all the nodes will b the same color whereas i'm looking to have nodes of different color depending on the situation.
the method for setting all Jtree nodes the same color(other than black):
tree.setCellRenderer(
new DefaultTreeCellRenderer() {
public Color getTextNonSelectionColor() {
return Color.lightGray; } });I WANT TO CHOSSE EACH COLOR FOR EACH NODE
help plz
thanksYou need to implement TreeCellRenderer interface
public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus)You can know which node is rendering by check value argument. Please read DefaultTreeCellRenderer's code. -
How to get the icon type of a JTree node, very urgent
hi,
i need to get the type of a JTree node but don't know how. this is quite an emergency. please help. thank you all.
-joeythere are several icons defined in the DefaultTreeCellRenderer class, such as closedIcon, leafIcon, openIcon. i was wondering if there is any way to get the icon type of a node. thanks for your reply.
-joey -
Please help with JTree Node Duplication
Iam building a JTree which should not allow node duplication.
1.)First i construct a ArrayList which stores all the previous nodes.
treeNodeNames=new ArrayList();
2.)i call the method
readTreeNodeNames((DefaultMutableTreeNode)dtm.getRoot());
3.)The method readTreeNodeNames is
public void readTreeNodeNames(DefaultMutableTreeNode node) {
if(node.toString().toLowerCase().length()!=0) {
treeNodeNames.add(node.toString().toLowerCase());
for(Enumeration en=node.children();en.hasMoreElements();) {
DefaultMutableTreeNode childNode=(DefaultMutableTreeNode)en.nextElement();
if(childNode.toString().toLowerCase().length()!=0) {
treeNodeNames.add(childNode.toString().toLowerCase());
if(!childNode.isLeaf()) {
readTreeNodeNames(childNode);
4.)i have four menu when right click a node add,modify,add subnode,delete.
node duplication fails in my case.when should i call this method?should i call while doing every above mentioned operations or in TreeModelEvent implementations?
i have mailed this problem already two times.but no one has not replied.Kinldy consider it and give me a solution.Or anyone having code for JTree Node duplication please send me to [email protected]Hi all,
Any ideas to overcome this problem.?
Thanks,
Krish -
How to get the TreePath of a JTree Node
hello all:
Given a DefaultMutableTreeNode JTree node, how i can
get the TreePath for it.
because I want to use this method to fire the function expandPath(TreePath path)
thank you very much!
-Daniel Markthank you I had got idea from forum
http://forum.java.sun.com/thread.jsp?forum=31&thread=381249
thx again.
-Daniel -
Can not highlight a JTree node programmatically
Hi Swing lovers,
I can select a node using setSelectionPath. Unfortunately I can not find a way to show the user that the node is selected. I know it can be done. When traversing the tree with the up- and down keyboard arrow, it shows what I want to see.
Am I overlooking some method here?
Thanks a lot for the tip,
ErikThanks DrClap,
I expected to find an easy way to mark a jTree node as being selected. However the TreeCellRenderer does the job. See the code snipped below:
public JTree jTree1 = new JTree();
private TreeNode currentNode = null;
//assing currentNode somewhere in you code
jTree1.setCellRenderer(new MyRenderer());
private class MyRenderer extends DefaultTreeCellRenderer {
public MyRenderer() {
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
if (currentNode != null) {
if (value.hashCode() == currentNode.hashCode()) sel = true;
super.getTreeCellRendererComponent(
tree, value, sel,
expanded, leaf, row,
hasFocus);
return this;
/ -
How to post an Event (mouse left click) to JTree node
Hi,
I am using JTree for my application just like the windows explorer tree. By default, Jtree node will got focus using left click. But, I'd like that my tree will detect a right click so that I can copy any file to the Jtree. I've added a mouselistener to it but the node is not selected by the right click. Anyboby can teach me how to post a mouse left click event to the Jtree so that it will become selected using left click.
Thanks a millionSee if this is useful
public void mouseClicked(MouseEvent event)
Object object = event.getSource();
if (object == mTree)
mTree_mouseClicked(event);
private void mTree_mouseClicked(MouseEvent event)
if(event.getModifiers()==event.BUTTON3_MASK)
//your logic goes here
}//close method -
How to hide node handles (legs) from JTree nodes?
Hello,
Does anyone has an idea on how to not display JTree node handles (legs)?
Thank you,
MindaugasYou can do it with Java/Metal look and feel by doing this:
JTree tree = new JTree(...);
tree.setClientProperty("JTree.lineStyle", "None");
For any other L&F, you will have to look at the UI code.
Mitch Goldstein
Author, Hardcore JFC -
Restricting Jtree node from collapsing.
Hi all,
Is there any way by which i can restrict a Jtree node from collapsing?
please help,
thx,
Soni.hi
i got it,
here is the solution
tree.addTreeWillExpandListener(new TreeWillExpandListener() {
public void treeWillExpand(TreeExpansionEvent e)throws ExpandVetoException {
public void treeWillCollapse(TreeExpansionEvent e)throws ExpandVetoException {
TreePath p = e.getPath();
DefaultMutableTreeNode n =
(DefaultMutableTreeNode)p.getLastPathComponent();
if (n == root) {
throw new ExpandVetoException(e);
-Soni
Maybe you are looking for
-
We have installed RM client in the POC server . Installed Deployment Agent in Dev server . We created Configuration stages for POC->Dev. We created a template with x copy deployer and selected source as build definition. While releasing we faced
-
D-Link Dir-615 internet problems
Hi All, I am not posting this for help. I came across a problem and could not find any help on the net that would solve it. So this is to help anyone whom might have similar problems. First, let me give you the scenario. I have SBC DSL as my ISP and
-
My iPad volume works on Facebook but not on games
My iPad volume works n everything but games
-
Why don't color values change when using proof colors?
Hi, i am very interested in obtaining exact replicas of the image in screen (in ProPhoto) and the image printed (using a suitable printer profile). However when I select Proof Colors from the view menu, the appearance changes but the RGBV or Lab colo
-
Hello, There are a lot of functions in the registry ( rfccache ). Which mechanisme fills this values. There are 2 different entries: Complete and FunctionExists. I had some users where p.ex. the FunctionExists - Value of Z_EASYDMS_FUNCT_GET_LIST cha