Finding a node in a JTree from a String
Searched the forums and didn't find anything....
I have a JTree constructed. Say it looks like this:
-Fruit
-Apple
-Green
-Red
-Orange
-Banana
I want to be able to get a hold of the Red node when the only information I have is a String that is "Fruit,Apple,Red".
I was trying to come up with a way to turn that String into a TreePath but can't seem to do it.
Any ideas?
Thanks for the response. Yes, I am using DefaultMutableTreeNodes, but iterating through the whole tree is not an option because there will be tens of thousands of nodes. Tens of thousands??? That's a lot of nodes. Still, even with 10,000 nodes, if you follow my advice and have the nodes nicely seperated into just two levels that gives you 100 top level nodes with 100 entries each. The max cost of your search is 200 (2n) which is pretty reasonable.
Also, it cannot be done faster unless your tree is sorted. (Although you could apply more threads and Executors)
Isn't there anyway to get a node from a String representation of a path without iteration?There is no "magic" in programming. Even if there were a method "getTreePathFromString", it would have to do what I'm telling you to do.
Similar Messages
-
Building JTrees from Filename strings????
Does anybody know or have code to build JTrees from fileName string so that the tree is expandable and uses expansion listeners.
Does anybody have code that allows you to show the local filesystem and also file strings contained say in a file so they can both be viewed at the same time. ie if you know somebody else has a file but you want it reflected in your local filesystem.
Come on somebody must -
Find a value and the position from the string.
Hi All,
Actually I have one table called test and it got 2 columns in it one is number and the other one is varchar2. now I need to find a particular value from a string and also the position of first position character of that searched value. For example, I need to search “Small” from the string “This is the small value” and also the position of that letter “S”.
The result should be ----
Value Position
Small 14
hare krishna
Alokuse substr(), instr() like this:
with
test as
select 1 as num, 'This is the small value' as str from dual union all
select 2 as num, 'This is the very-very small_value' as str from dual
select num, str,
substr(substr(str, instr(str, 'small', 1, 1)), 1,
nvl(nullif(instr(substr(str, instr(str, 'small', 1, 1)), ' ', 1, 1),0),
length(str)) - 1) as value,
instr(str, 'small', 1, 1) as position
from test
Query finished, retrieving results...
NUM STR VALUE POSITION
1 This is the small value small 13
2 This is the very-very small_value small_value 23
2 row(s) retrieved -
Confusion building JTree from path strings
If I have a bunch of strings like this:
"/dira/dir1/file1"
"/dira/dir1/file2"
"/dira/dir2/file1"
"/dira/dir3/anotherdir/file1"
etc.
Does anybody have an easy solution to getting them in a JTree that looks like this:
dira
|
+-dir1
| |
| +-file1
| |
| +-file2
|
+-dir2
| |
| +-file1
|
+-dir3
|
+-anotherdir
|
+-file1Mainly I am having trouble getting the tree to populate without duplicating nodes. For example dir1 gets listed twice. I am looking for a solution that will parse these strings and build the tree. I have found demos that read a file system, but nothing that works with strings. I have tried to pick apart the file system demos, but so far I can't get it to work correctly.
Thanks,
JeffThis compiles and works (with 1.4):
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.util.HashMap;
public class TreeStrings extends JFrame {
public TreeStrings() {
super("Tree strings");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 400);
String[] inputStrings = {"/dira/dir1/file1", "/dira/dir2/file1", "/dira/dir2/file2"}; // your bunch of Strings
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("www");
HashMap nodeMap = new HashMap();
for(int i = 0; i < inputStrings.length; i++) {
String s = inputStrings;
DefaultMutableTreeNode lastNode = rootNode;
int lastIndex = 0;
while(true) {
DefaultMutableTreeNode tempNode = null;
int nextIndex = s.indexOf("/", lastIndex + 1); // <- i forgot + 1
if(nextIndex != -1) { //we are somewhere in middle of s, checking nodes from root to leaf, one by one.
String nodeKey = s.substring(0, nextIndex);
if(nodeMap.get(nodeKey) == null) { //no such node, must make one
String nodeName = s.substring(lastIndex, nextIndex); // you want the last nodeKey word for node name
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(nodeName);
nodeMap.put(nodeKey, newNode);
lastNode.add(newNode);
lastNode = newNode;
else { //allready such node, just put it to be lastNode
lastNode = (DefaultMutableTreeNode) nodeMap.get(nodeKey);
lastIndex = nextIndex;
else { //no more "/" , it means we are at end of s, and that all parent nodes for this leaf-node exist.
// and we just add the leaf node to last node
String leafName = s.substring(lastIndex, s.length());
DefaultMutableTreeNode leafNode = new DefaultMutableTreeNode(leafName);
lastNode.add(leafNode);
break; // go to next s
//You first make your tree structure with DefaultMutableNodes,
//Then make a DefaultTreeModel with the root node,
//Then make a Tree with the DefaultTreeModel
DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
JTree yourTree = new JTree(treeModel);
getContentPane().add(yourTree, BorderLayout.CENTER);
show();
public static void main(String[] args) {
new TreeStrings();
Anything else? -
Hello,
How i can i find duplicate nodes in a JTree. And give out a message that the node already exists.
Thanks.
Reg,
suriThe first you have to defind what is dublicating, because the node in the tree is a node itself (e.g. with label node name and icon) and node can have user object that can contains some defind logics and attributes like ID. And then if you just want to not alow to have node with the same name you will check node label. But if you want avoid adding the node with the same user object you have to implement some comparation mechanism on the node or user object lavel.
Hope will help. -
How to select a node in a JTree by name
I have a JTree in my program. I want to programmatically set one of these nodes selected by the name of the node. I do not know how to do this. I read the "How to use trees", but no help
Thanks!I have a JTree and each node on the JTree has a string name. I also have a JEditorPane that lists all these names at start up. If the user clicks on one of these names, I want to catch the HyperlinkEvent and automatically select that node in the JTree.
So in short, I have the String name of the node that I want to programatically select.
Thanks! -
Move node and its silings from one jtree to another
Hi,
I am trying to move JTree nodes and its siblings from one JTree to another. If anyone has the code, please post it on the website or mail to [email protected]
Thanks
PavanPavan,
You may have to do a sanity check before adding it.
Better run the program in a debugger and have a break point at the clipBoard.put() line. Else system.out.println() lines will kill enormouse programming time rather than using debugger.
Also in following this thread, i found that you may have to be bit more thorough with the DefaultMutableTreeNode class first.
Thanks,
ananth
Thomas,
for (int p = 0; p < jtree.getSelectionCount(); p++) {
System.out.println(".3.......p= "+p);
node =
=
(EuamDefaultMutableTreeNode)paths[p].getLastPathCompon
nt();
clipBoard.put(node.toString(), node);
System.out.println(".4...........");
Giving error at clipBoard.put()
line....java.lang.NullPointerException
..Any idea why?
Thanks.
Pavan -
Hi,
Is it possible to hide a particular node in a JTree? (i dont mean collapsing a node) ie to make some node invisible?Plz reply, deadline's coming.
Thanks in advance,
-Adhiraj.If I need to "hide" a node, I find easier to remove it from a tree.
Denis Krukovsky
http://dotuseful.sourceforge.net/ -
Hello everyone,
I have to build a JTree from a table data from database. The table structure is
(id,parent_id,name). In order to build the tree, I have to the following 2 loop searching for the parent_id
while (i<size){
while(j<size){
//find it's parent_id
j++;
i++;
It is too slow! Can anyone help me?
Thanks!
--tcYou just add children to whatever the parent node is for that object.DefaultMutableTreeNode root = new DefaultMutableTreeNode();
child1 = new DefaultMutableTreeNode();
root.add( child1 );
grandChild = new DefaultMutableTreeNode();
child1.add( grandChild );
greatGrandChild = new DefaultMutableTreeNode();
grandChild.add( greatGrandChild );Etc. -
Where do I find the "Node Manager" service?
Can anyone tell me where to find the "Node Manager Service" In Call Manager 5.1.2 or IPCC 4.5?
My db_CRA database in IPCC is not updating the real time ICD statistics table and Bug CSCsc09160 seems to indicate that stopping and starting the "Node Managers" may fix the issue.
From the bug report:
Symptom:
Under the db_cra two tables (RtCSQsSummary and RtICDStatistics) are not updating. They stop updating concurrently with engine failovers and reboots. Only a hard reboot or a
service failover brings them back into an active state.
When the RtCSQsSummary and RtICDStatistics tables do update on the
primary DB they do not update on the secondary DB and the data on them
doesnt get refreshed.
Conditions:
stopping Node manager on node 1, data fails to be written to node 2. Then when we start NM back up on node 1 data is still not written to either data store
Workaround:
Not much as a workaround, because the solution requirs stop on both Node
Managers and bring up node 1 first and the data starts writing to DB
again.
Thanks,
BrianPost Author: jsanzone
CA Forum: Authentication
Sven,
The reference to Session Manager is more of a concept of operations versus an entity. The portion of code that you copied and pasted in your post is actually part of the verbiage used in an ASP script that BusinessObjects expects you to create in order for you to obtain your objective. You can use this coding to create your own customized script or you might be able to search around on the web for a more complete solution. -
How to get total number of nodes in a JTree?
Hi,
I am trying to get total number of nodes in a JTree, and cannot find a way to do it.
The current getRowCount() method returns the number of rows that are currently being displayed.
Is there a way to do this or I am missing something?
thanks,How many nodes does this tree have?
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.*;
public class BigTree {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
TreeModel model = new TreeModel() {
private String node = "Node!";
@Override
public void valueForPathChanged(TreePath path,
Object newValue) {
// not mutable
@Override
public void removeTreeModelListener(TreeModelListener l) {
// not mutable
@Override
public boolean isLeaf(Object node) {
return false;
@Override
public Object getRoot() {
return node;
@Override
public int getIndexOfChild(Object parent, Object child) {
return child == node ? 0 : -1;
@Override
public int getChildCount(Object parent) {
return 1;
@Override
public Object getChild(Object parent, int index) {
return node;
@Override
public void addTreeModelListener(TreeModelListener l) {
// not mutable
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(new JTree(model)));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}But for bounded tree model using DefaultMutableTreeNode look at bread/depth/preorder enumeration methods to walk the entire tree. Or look at the source code for those and adapt them to work with the TreeModel interface. -
How to use custom nodes in a JTree without reinventing the wheel?
Hello,
Each node contains two JTextAreas in a Box layout and a few JButtons.
I wish to display these nodes in a JTree.
Reading the tutorial, it seems I would have to reimplement the TreeModel, TreeCellRenderer/Editor, MutableTreeNode interfaces etc.
Can I use the DefaultTreeModel, and other standard widgets (great stuff!) to minimize the amount of reimplementation I must do. aka avoid reinventing the wheel? I was thinking of extending my node from the DefaultMutableTreeNode class - however it does not display the nodes with the TextAreas, buttons etc.
any help appreciated.
thanks,
Anilwas able to fix it over here:
http://forum.java.sun.com/thread.jspa?messageID=4089777 -
How can I get a count of ALL nodes in a JTree?
Not sure if I am missing something here or what. Is there an easy way to determine the total number of nodes in a JTree? I thought there would be a method to return this, but I'm not seeing it in JTree or DefaultTreeModel. Do I have to start at the root and recursively get child counts? Yuck!
JamieYou are absolutely right! Create a recursive method and count all your children from the root.
Denis Krukovsky
http://dotuseful.sourceforge.net/ -
Okay, perhaps I am sidetracked today by all the sad craziness occuring in New York and DC, or perhaps I just don't have a grasp on JTrees yet...but...
I have implemented a TreeCellRender to create panels with buttons and other information to be the nodes of a JTree I created. Everything shows up beautifully, however, I want the buttons on this panel to depress and perfom actions (work like normal) when the user clicks/selects such a button in the tree structure. I can't figure out how to properly set up event handlers to get from the tree to the tree node to the "bean" I'm using as a node. If anyone has any helpful hints, I'd appreciate it!
Thanks in advance!add actionlistener to the JTree, and then get the object by getLastPathComponent, and compare it if its the button and do the action.
-
Building jtree from database query
I am trying to build a JTREE from a database result-set. The resultset is listed below. I'm thinking I can somehow build a dynamic array of objects to build a TreePath, then use that to build the JTREE. Any input is appreciated.
ResultSet Output:
Here is how the results would be retrieved from the database (including the order of the output).
usr 1
local 2
sbin 2 file4
bin 3 file1
bin 3 file2
logs 3 file3
tmpdir 4
The first column is the directory name, the second column is the directory/file level/position, and the third column is the filename, if one exists.
So from above:
/usr/local/sbin has file "file4"
/usr/local/bin has files "file1" and "file2"
/usr/local/logs has file "file3" and directory "tmpdir"
How could I gather this information into an appropriate structure and create a JTREE from it.
Thanks.
-JimSo each line would:basically...
If I don't know the entire path of the parent (because I've read in a
line that only has the "one-up" parent name) .... However, when I
read the line from the database result-set, I don't know where "local" is.See... that's another problem with that data. Maybe you know cuz it's the last node if it's all in a proper order. In which case maybe you only need to hold the last parent node... Some recursive function would be useful.
If I were going to store the data, I would store either the name as a full path:
/usr
/usr/local
/usr/loca/bin
or
usr /
local /usr
bin /usr/local
If you have that, it might be easier to figure out without having to worry about what belongs where.
Maybe you are looking for
-
Really fed up with multiple apple ID's and email addresses
I've been an apple product user for the best part of 5 years and I have two apple ID's, multiple iCloud alias's and a number of associated email addresses. Two questions: Can all of my ID's be merged in to one account? If not: Can I create a new appl
-
Server Response: 550 5.7.1 Unable to relay
SBS 2011 I have exchange 2010, Internally Outlook send/ Receive working fine-- Local Ip address. Owa Send/Receive working fine. But remote user can receive the Emails, But cant send the emails. Subject 'tes' Server Error: 550 Server Response: 550 5.7
-
How to restore original size of placed and fitted image?
If an image is placed to the frame, fitted to it, file saved. When I open it again, is there the way to restore the original size of the image? Thank you in advance for any help. Vera
-
Hello. On my home screen on the E72 the words (ie MENU, CONTACTS etc) are partially cut off height wise. I have reduced all the font sizes to standard but still on my home screen the letters/ numbers for the time seem cut down in height, is this norm
-
Every time I create a hyperlink url and then enable it- the url deletes itself or switches to another url- please help ! thanks