How do I change the "root" directories name in JTree? - java

I have a simple implementation of JTree:
tree1 = new JTree(LibObj.collectionToStringArray(LibObj.books));
tree1.setRootVisible(true);
scrollPane2 = new JScrollPane(tree1);
scrollPane2.setPreferredSize(new Dimension(350, 300));
panel.add(scrollPane2);
LibObj.collectionToStringArray(LibObj.books) is a method in another class that takes a collection and turns it into an array of strings
Everything is displaying as expected but the root directory is named "Root". How do I change the name? (I want it to be called Books)

Using the constructor JTree(TreeNode node) would give you the chance to create your own root node.
Just like this:
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root node name");
for( String book : booksArray ) {
DefaultMutableTreeNode bookNode = new DefaultMutableTreeNode(book);
rootNode.add(bookNode);
}
tree1 = new JTree(rootNode);
tree1.setRootVisible(true);
[...]

Related

Selecting the leaf of jtree that will open another jrame in netbeans

Good day,
I am trying to create a tree view in order to display for the user the other j Frames in Netbeans.
When the user select a leaf, it will display for him the required forum.
What I am facing right now that when selecting the other leaves, it is display for me all forums.
Here is my codes
private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
jTree1.getLastSelectedPathComponent();
if (node == null) return;
Object nodeInfo = node.getUserObject();
jTree1.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
JTree tree = new JTree();
Employee emp = new Employee();
rectutment rec = new rectutment();
interview inter = new interview();
DefaultMutableTreeNode firstLeaf = ((DefaultMutableTreeNode)tree.getModel().getRoot()).getFirstLeaf();
tree.setSelectionPath(new TreePath(firstLeaf.getPath()));
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
root.add(firstLeaf);
firstLeaf.add(new DefaultMutableTreeNode("firstleaf"));
model.reload();
emp.add(tree);
emp.pack();
emp.setVisible(true);
if ( emp.isActive()&& rec.isActive()){
emp.dispose();
}
else{
rec.dispose();
}
rec.setDefaultCloseOperation(emp.EXIT_ON_CLOSE);
rec.setLocationRelativeTo(emp);
rec.add(tree);
rec.pack();
rec.setVisible(true);
}
Any ideas?

Java Swing > Calling specific powershell script by selecting DefaultMutableTreeNode from Jtree model

I'm having my first time with java Swing and I wondering if can I add values for each DefaultMutableTreeNode and refer to them by selecting specific node?
e.g. Calling specific powershell script by selecting node from Jtree model (1 node = 1 script).
I'm really newbie and I will be greatful if somebody could explain or redirected me to some solution ;p
private JTree setTab2Tree() {
JTree tree;
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Customers");
DefaultMutableTreeNode webClient = new DefaultMutableTreeNode("Web");
webClient.add(new DefaultMutableTreeNode("Person Customer"));
webClient.add(new DefaultMutableTreeNode("Firm Customer"));
DefaultMutableTreeNode appClient = new DefaultMutableTreeNode("App");
appClient.add(new DefaultMutableTreeNode("Person Customer"));
appClient.add(new DefaultMutableTreeNode("Firm Customer"));
root.insert(webClient, 0);
root.insert(appClient, 1);
tree = new JTree(root);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(new MainTree.SelectionListener());
tree.setBorder(BorderFactory.createLineBorder(Color.black));
add(new JScrollPane(tree));
}

Breadth First Neo4j tree traversal and TreeNode creation

I have a Neo4j graph database which maps a file system structure consisting of nodes representing folders and files.
Each node has a FATHER_OF and a CHILD_OF relationship.
Now I need to create a TreeNode structure in Java starting from the Neo4j graph: currently I implemented a breadth first print of the NEO4J structure as follows:
public Traverser getTraverser()
{
Transaction tx = graphDb.beginTx();
Traverser traverser = traverseStorage(rootNode);
return traverser;
}
private static Traverser traverseStorage(final Node startNode) {
TraversalDescription td = Traversal.description()
.breadthFirst()
.relationships(GraphStorage.RelTypes.FATHER_OF, Direction.OUTGOING);
return td.traverse(startNode);
}
Now I'm trying to create a Tree using the above breadth-first traverser but can't figure out how to properly assign the correct parent to each node.
TreeNode root = new DefaultTreeNode("root", null);
Traverser traverser = graphStorage.getTraverser();
TreeNode parent = root;
for (Path directoryPath : traverser) {
DefaultTreeNode tmp1 = new DefaultTreeNode((String)directoryPath.endNode().getProperty("name"), parent);
}
I hoped there was something like directoryPath.endNode().getParent() but apparently there isn't.
I'm searching for a solution which doesn't require me to use Cypher query language, any help?
Ok found out, just need a HashMap to map Neo4j node id's to TreeNode objects:
HashMap<Long, TreeNode> treeNodeMap = new HashMap();
then the rest becomes:
TreeNode root = new DefaultTreeNode("root", null);
Traverser traverser = graphStorage.getTraverser();
TreeNode parent = root;
Relationship parentRelationship = directoryPath.endNode().getSingleRelationship(
GraphStorage.RelTypes.CHILD_OF, Direction.OUTGOING);
if (parentRelationship != null) {
Node parentFileNode = parentRelationship.getEndNode();
if (parentFileNode != null) {
long parentId = parentFileNode.getId();
parent = treeNodeMap.get(new Long(parentId));
}
DefaultTreeNode tmp1 = new DefaultTreeNode((String)directoryPath.endNode().getProperty("name"), parent);
treeNodeMap.put(new Long(directoryPath.endNode().getId()), tmp1);
}
The above correctly works.

JSF/ICEfaces Dynamic hierarchy tree example

i have list of departments and each department might have a parent or not,department domain object is as follows:
- departmentId
- parentDepartmentId (null if current department has no parent i,e should be under root directly, and have value if current department have parent).
.
.
.
looking at icefaces tutorial code for creating basic tree:
// create root node with its children expanded
DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode();
IceUserObject rootObject = new IceUserObject(rootTreeNode);
rootObject.setText("Root Node");
rootObject.setExpanded(true);
rootTreeNode.setUserObject(rootObject);
// model is accessed by by the ice:tree component via a getter method, this object is what's needed in the view to display the tree
model = new DefaultTreeModel(rootTreeNode);
// add some child nodes
for (int i = 0; i <3; i++) {
DefaultMutableTreeNode branchNode = new DefaultMutableTreeNode();
IceUserObject branchObject = new IceUserObject(branchNode);
branchObject.setText("node-" + i);
branchNode.setUserObject(branchObject);
rootTreeNode.add(branchNode);
}
it's all about constructing basic node, and adding childs.
my case is complex that child A which is under root may have child nodes B,C,D and D have for example child nodes and so on so on.
so i am thinking of a best practice about how to accomplish something like that, i need a sample code or hints if anyone can help.
You would need a recursive method to construct the tree from your model.
public void buildRecursiveTreeNode(DefaultMutableTreeNode parentTreeNode,
String treeId, String treeName, GenericTreeVo modelVo)
{
// if the database model contains more children.
// add the current nodes first and pass in this nodes tree id and name to construct the children for this parent nodes.
}
Updated answer to include recursion example.
http://www.danzig.us/java_class/recursion.html
just added a recursion link, all I am saying is when you iterate the data from the database, you would see if you have any child records, if you have child records you would call the same method by passing the DefaultMutableTreeNode and that would become the parent.
finally i was able to do it as follows:
List<Department> departmentList = getAllDepartments();
// create root node with its children expanded
DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode();
IceUserObject rootObject = new IceUserObject(rootTreeNode);
rootObject.setText("Root");
rootObject.setExpanded(true);
rootTreeNode.setUserObject(rootObject);
HashMap<Department, DefaultMutableTreeNode> createdNodesMap = new HashMap<Department, DefaultMutableTreeNode>(
0);
for (Department department : departmentList) {
DefaultMutableTreeNode currentNode = null;
if (createdNodesMap.get(department) == null) {
log.debug("############ CREATING NODE "
+ department.getName());
currentNode = new DefaultMutableTreeNode();
IceUserObject currentObject = new IceUserObject(currentNode);
currentObject.setText(department.getName());
currentObject.setExpanded(true);
currentNode.setUserObject(currentObject);
if (department.getParentDepartment() == null) {
rootTreeNode.add(currentNode);
log.debug("######### NODE " + department.getName()
+ " ADDED UNDER ROOT");
}
createdNodesMap.put(department, currentNode);
} else {
log.debug("############ GETTING CREATED NODE "
+ department.getName());
currentNode = createdNodesMap.get(department);
}
if (department.getChildren().size() > 0)
log.debug("############ NODE " + department.getName()
+ " HAVE " + department.getChildren().size()
+ " CHILDREN");
else
log.debug("############ NODE " + department.getName()
+ " DOES NOT HAVE CHILDREN");
for (Department department2 : department.getChildren()) {
log.debug("############ CREATING CHILD "
+ department2.getName() + " FOR PARENT "
+ department.getName());
DefaultMutableTreeNode branchNode;
if (createdNodesMap.get(department2) == null) {
branchNode = new DefaultMutableTreeNode();
IceUserObject branchObject = new IceUserObject(
branchNode);
branchObject.setText(department2.getName());
branchObject.setExpanded(true);
branchNode.setUserObject(branchObject);
} else
branchNode = createdNodesMap.get(department2);
createdNodesMap.put(department2, branchNode);
currentNode.add(branchNode);
}
}
model = new DefaultTreeModel(rootTreeNode);
Check http://click.avoka.com/click-examples/tree/checkbox-tree-page.htm
The latter is done via the Apache Click framework. Right now I'm developing a project where this data structure (hierarchy tree) is heavily used. You can set the root node or if you need to have several starting points, you can create a wildcard root node that won't affect the functionality, the subclasses, like others have commented, need to be created recursively.

Display JTree using a single node element having full content

I have a single node that has all the child nodes and attributes in the following format.
node = Root[
attributes = {rootattribute1, rootattribute2,...},
value = [100,
childNode1
[
attributes = {childNode2att1,.....}
value = [1001]
]
childNode2
[
attributes = {childNode2attributes,.....}
value = [1001]
] ......... and some other childnodes like this
]
When I use Jtree tree = new Jtree(node); It is creating just a single rootelement for the tree showing all these details within a single row of a tree.
Instead I want to display the tree in the correct hierarchy with nested child nodes and atrribute values. Is there any inbuilt method to do this ?
If there is no inbuilt method to do this how do I write the code for this ?
PS: the node content displayed above is dynamic and is not static.
You can start with something like:
import javax.swing.*
import javax.swing.tree.*
class Root {
def attributes = []
def children = []
def value = 0
def String toString() {
"[${value}] attributes: ${attributes} children: ${children}"
}
}
def createTreeNode(node) {
def top = new DefaultMutableTreeNode(node.value)
for (attr in node.attributes) {
top.add(new DefaultMutableTreeNode(attr))
}
for (child in node.children) {
top.add(createTreeNode(child))
}
top
}
root = new Root(
attributes: ['rootattribute1', 'rootattribute2'],
value: 100,
children: [
new Root(
attributes: ['childNode2att1'],
value: 1001),
new Root(
attributes: ['childNode2attributes'],
value: 1002),
])
frame = new JFrame('Tree Test')
frame.setSize(300, 300)
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
jtree = new JTree(createTreeNode(root))
frame.add(jtree)
frame.show()
JTree is a sophisticated component - please read the JTree Swing Tutorial for more details on how to customize the tree for your exact needs.

Categories

Resources