• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 653
  • Last Modified:

displaying data in the jtextfield at the user selection from a jtree

hello,

I have designed a java application with a jtree control and jtextfields, im able to retreive data into the tree from the oracle DB, now i want to display related data when user selects particular node.

any help would be greatly appreciatted.

thanks.
0
vihar123
Asked:
vihar123
  • 35
  • 31
  • 27
  • +2
2 Solutions
 
expertmbCommented:
on selction event or item change event write the selected node value to textfield.
0
 
CEHJCommented:
0
 
vihar123Author Commented:
can u give me an example please, im quite new to java
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
CEHJCommented:
>>can u give me an example please

See above
0
 
expertmbCommented:
ahve a look at it
http://javaalmanac.com/egs/javax.swing.tree/SelectTree.html


tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent evt) {
            // Get all nodes whose selection status has changed
            TreePath[] paths = evt.getPaths();
   
            // Iterate through all affected nodes
            for (int i=0; i<paths.length; i++) {
                if (evt.isAddedPath(i)) {
                    // This node has been selected
                    textfield.setText(node.getNodeValue());
                  } else {
                    // This node has been deselected
                }
            }
        }
    });
0
 
girionisCommented:
If "tree" if your JTree you could do:

tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent evt) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            System.out.println("info: " + node.getNodeName());
        }
    });
0
 
expertmbCommented:
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
textField.setText(node.toString());
0
 
vihar123Author Commented:
when im using this, its giving me as cannot resolve symbol
--------------------------


       while (rset.next())
               {
                              
                DefaultMutableTreeNode name1 = new DefaultMutableTreeNode(rset.getString("emp_name"));
              topnode.add(name1);
              DefaultMutableTreeNode salary = new DefaultMutableTreeNode(rset.getString("emp_sal"));
              name1.add(salary);
              DefaultMutableTreeNode commission = new DefaultMutableTreeNode(rset.getString("emp_comm"));
              salary.add(commission);

               }
               
         
       
       jTree1 = new javax.swing.JTree(treeModel);

      jTree1 = new javax.swing.JTree(topnode);
       
                         jTree1 = new javax.swing.JTree(treeModel);
                    jTree1.setRootVisible(true);
                    treeModel.reload();

                  
        }
                 
        catch (SQLException e)
        {
            System.out.println(e);
        }
       
    jTree1.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent evt) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            System.out.println("info: " + node.getNodeName());
        }
    });
0
 
girionisCommented:
> tree.getLastSelectedPathComponent();
should be

jTree1.getLastSelectedPathComponent();
0
 
CEHJCommented:
>>its giving me as cannot resolve symbol

Which symbol?
0
 
vihar123Author Commented:
above one was i didnt import event class,

but still its not identifying these methods, getNodeName() and getNodeValue()

--------

jTree1.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent evt) {
         
            TreePath[] paths = evt.getPaths();
             
            for (int i=0; i<paths.length; i++) {
                if (evt.isAddedPath(i)) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                    System.out.println("info: " + node.getNodeName());
                    jTextField1.setText(node.getNodeValue());
                  } else {
   
                }
            }
        }
    });
0
 
CEHJCommented:
You should use getUserObject:

System.out.println("info: " + node.getUserObject());
0
 
CEHJCommented:
String info = node.getUserObject().toString();
System.out.println("info: " + info);
jTextField1.setText(info);
0
 
girionisCommented:
I think a simple toString as also suggested by expertmb would do too.
0
 
CEHJCommented:
>>I think a simple toString as also suggested by expertmb would do too.

Yes, although if vihar123 wants to extend his implementation, he may want to use a class to contain info other than just the name, in which case a wrapped use object would be good
0
 
girionisCommented:
Yes true.
0
 
vihar123Author Commented:
its not giving any output, but its running

----------------------------------------------------

jTree1.getSelectionModel().setSelectionMode
            (TreeSelectionModel.SINGLE_TREE_SELECTION);
   
    jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent evt) {
                            jTree1.addTreeSelectionListener(this);
                        TreePath[] paths = evt.getPaths();
             
            for (int i=0; i<paths.length; i++) {
                if (evt.isAddedPath(i)) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                   
                    String info = node.getUserObject().toString();
                              System.out.println("info: " + info);
                              jTextField1.setText(info);
                              jTextField1.setVisible(true);
                              jTextField1.getComponentListeners();

                  } else {
   
                }
            }
        }
    });
0
 
girionisCommented:
It is probably not entering the loop since nodes' status has not changed. Try a simpel example:

jTree1.getSelectionModel().setSelectionMode
            (TreeSelectionModel.SINGLE_TREE_SELECTION);
   
    jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent evt) {
                         
                                 DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                   
                    String info = node.getUserObject().toString();
                         System.out.println("info: " + info);
             
                   }
        }
    });

and tell us if this works. You also do not need this line:

jTree1.addTreeSelectionListener(this);

0
 
CEHJCommented:
>>jTree1.addTreeSelectionListener(this);

This is unnecessary. Replace it with this

System.out.println("Tree selection occurred");
0
 
girionisCommented:
You do not need the above line since you are already registering a listener to the tree.
0
 
CEHJCommented:
Get rid of this if block:

if (evt.isAddedPath(i)) {
}
0
 
vihar123Author Commented:
its not enterting into the loop itself, i dont understand why......
---------

while (rset.next())
               {
                              
                DefaultMutableTreeNode name1 = new DefaultMutableTreeNode(rset.getString("emp_name"));
              topnode.add(name1);
              DefaultMutableTreeNode salary = new DefaultMutableTreeNode(rset.getString("emp_sal"));
              name1.add(salary);
              DefaultMutableTreeNode commission = new DefaultMutableTreeNode(rset.getString("emp_comm"));
              salary.add(commission);

               }
               
         
       
       jTree1 = new javax.swing.JTree(treeModel);

      jTree1 = new javax.swing.JTree(topnode);
       
                         jTree1 = new javax.swing.JTree(treeModel);
                    jTree1.setRootVisible(true);
                    treeModel.reload();
                   
            jTree1.getSelectionModel().setSelectionMode
            (TreeSelectionModel.SINGLE_TREE_SELECTION);
   
          jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent evt) {
                         System.out.println("info: " );
                                 DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                   
                    String info = node.getUserObject().toString();
                         System.out.println("info: " + info);
             
                   }
       
    });
                  
        }
                 
        catch (SQLException e)
        {
            System.out.println(e);
        }
0
 
CEHJCommented:
Simplest would be to do:

                      TreePath tp = evt.getPath();
                      System.out.println(tp.getLastPathComponent().toString());
0
 
girionisCommented:
Why do you have the loop, what are you trying to achieve?

YOu can also put that piece of code:

  jTree1.getSelectionModel().setSelectionMode
            (TreeSelectionModel.SINGLE_TREE_SELECTION);
   
         jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent evt) {
                         System.out.println("info: " );
                                 DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                   
                    String info = node.getUserObject().toString();
                         System.out.println("info: " + info);
             
                   }
       
    });

outside your try (I guess) block of code. Better keep clear the design.
0
 
CEHJCommented:
You're creating a tree 3 times and assigning to one reference!

>>
jTree1 = new javax.swing.JTree(treeModel);

     jTree1 = new javax.swing.JTree(topnode);
       
                     jTree1 = new javax.swing.JTree(treeModel);
>>
0
 
CEHJCommented:
Just create one tree and add nodes to it
0
 
girionisCommented:
Hehe yes, CEHJ is right, you do not need to create the tree three times, although it still should have got the last one.
0
 
vihar123Author Commented:
still not change....any new ideas or ways of doing it.......


jTree1.getSelectionModel().setSelectionMode
            (TreeSelectionModel.SINGLE_TREE_SELECTION);
   
          jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent evt) {
                         System.out.println("info: " );
                         TreePath tp = evt.getPath();
                      System.out.println(tp.getLastPathComponent().toString());

                                 DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                   
                    String info = node.getUserObject().toString();
                         System.out.println("info: " + info);
             
                   }
       
    });      
0
 
girionisCommented:
Does this work at all?

 jTree1.getSelectionModel().setSelectionMode
            (TreeSelectionModel.SINGLE_TREE_SELECTION);
   
         jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent evt) {
                         System.out.println("info: " );
                                 DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                   
                    String info = node.getUserObject().toString();
                         System.out.println("info: " + info);
             
                   }
       
    });

0
 
vihar123Author Commented:
not its nor working at all though i tried this specially.......

-------

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.*;
import javax.swing.event.*;
import javax.swing.tree.TreeNode;
import java.sql.*;


public class treelistener extends javax.swing.JFrame {

    private JTree jTree1;
public treelistener() {
        initComponents();
    }

public void initComponents()
{    
   
   
    javax.swing.tree.DefaultMutableTreeNode topnode = new javax.swing.tree.DefaultMutableTreeNode("Project Nr");
       
                                    
        DefaultTreeModel treeModel = new DefaultTreeModel(topnode);
       
       jTree1 = new javax.swing.JTree(treeModel);

      jTree1 = new javax.swing.JTree(topnode);
       
        try
        {
            DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
                     
           
            Connection conn =
            DriverManager.getConnection ("jdbc:oracle:thin:@fe64700:1521:tanska","anska_test", "praktikant2004");
           
            Statement stmt = conn.createStatement ();
                ResultSet rset = stmt.executeQuery("select * from emp1");
           

           
                    while (rset.next())
               {
                              
                DefaultMutableTreeNode name1 = new DefaultMutableTreeNode(rset.getString("emp_name"));
              topnode.add(name1);
              DefaultMutableTreeNode salary = new DefaultMutableTreeNode(rset.getString("emp_sal"));
              name1.add(salary);
              DefaultMutableTreeNode commission = new DefaultMutableTreeNode(rset.getString("emp_comm"));
              salary.add(commission);

               }
               
         
       
       jTree1 = new javax.swing.JTree(treeModel);

      jTree1 = new javax.swing.JTree(topnode);
       
                         jTree1 = new javax.swing.JTree(treeModel);
                    jTree1.setRootVisible(true);
                    treeModel.reload();
             
             
            
                  
        }
                 
        catch (SQLException e)
        {
            System.out.println(e);
        }
       
        jTree1.getSelectionModel().setSelectionMode
            (TreeSelectionModel.SINGLE_TREE_SELECTION);
   
         jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent evt) {
                         System.out.println("info: " );
                                 DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                   
                    String info = node.getUserObject().toString();
                         System.out.println("info: " + info);
             
                   }
       
    });
}
public static void main(String args[]) {
        setDefaultLookAndFeelDecorated(true);
             
        new treelistener();
       
       
       
                                                          }

}
0
 
CEHJCommented:
In that code, you create the tree five times. See my last comment
0
 
JohnnyAffaCommented:
class YourClass implements TreeSelectionListener
{
   JTree jTree;

   public YourClass()
   {
      jTree.addTreeSelectionListener(this);
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");

      root.add(new DefaultMutableTreeNode("branch 1");
      root.add(new DefaultMutableTreeNode("branch 2");
      root.add(new DefaultMutableTreeNode("branch 3");

     jTree = new JTree(root);

// to creats sub branches use
    DefaultMutableTreeNode level1 = new DefaultMutableTreeNode("level1");
    level1.add(new DefaultMutableTreeNode("level1 - 0");
    level1.add(new DefaultMutableTreeNode("level1 - 2");

    root.add(level1);

     jTree = new JTree(root);

   }

public void valueChanged(TreeSelectionEvent event)
{
   String item = event.getPath().getLastPathComponent().toString();

   if ( item.equals("level1 - 0") )
          System.out.println(" level1 -0 SELECTED");
}
0
 
CEHJCommented:
>>jTree.addTreeSelectionListener(this);

should appear after

>>jTree = new JTree(root);

in that last example


0
 
vihar123Author Commented:
ok heres is my latest and complete code, i have done all the changes.....but no result, what all im trying is to display the data on users selection.

-------------------------------------------------------



import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.*;
import javax.swing.event.*;
import javax.swing.tree.TreeNode;
import java.sql.*;
   

public class gui2 extends javax.swing.JFrame {

 // Variables declaration
   
private JTextField jTextField1;
private JTree jTree1;
private Connection connect;
private DefaultMutableTreeNode topnode;
      
      
      
      
    /** Creates new form GUI */
    public gui2() {
        initComponents();
    }
   
    private void initComponents() {
        jTextField1 = new javax.swing.JTextField();
          /*tree design and declarations*/
   
         
       
       javax.swing.tree.DefaultMutableTreeNode topnode = new javax.swing.tree.DefaultMutableTreeNode("Project Nr");
       
                                    
        DefaultTreeModel treeModel = new DefaultTreeModel(topnode);
       
       jTree1 = new javax.swing.JTree(treeModel);

 
       
       
        setTitle("Anska Maske");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

             
        /****  database connectivitiy *****/
       
        try
        {
            DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
                     
           
            Connection conn =
            DriverManager.getConnection ("jdbc:oracle:thin:@fe64700:1521:tanska","anska_test", "praktikant2004");
           
            Statement stmt = conn.createStatement ();
                ResultSet rset = stmt.executeQuery("select * from emp1");
           

           
                    while (rset.next())
               {
                              
                DefaultMutableTreeNode name1 = new DefaultMutableTreeNode(rset.getString("emp_name"));
              topnode.add(name1);
              DefaultMutableTreeNode salary = new DefaultMutableTreeNode(rset.getString("emp_sal"));
              name1.add(salary);
              DefaultMutableTreeNode commission = new DefaultMutableTreeNode(rset.getString("emp_comm"));
              salary.add(commission);

               }        
       
                         
                    jTree1.setRootVisible(true);
                    treeModel.reload();
             
             
            
                  
        }
                 
        catch (SQLException e)
        {
            System.out.println(e);
        }
       
   
    jTree1.getSelectionModel().setSelectionMode
            (TreeSelectionModel.SINGLE_TREE_SELECTION);
   
          jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent evt) {
                         System.out.println("info: " );
                       
                                 DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                   
                    String info = node.getUserObject().toString();
                         System.out.println("info: " + info);
                          TreePath tp = evt.getPath();
                      System.out.println(tp.getLastPathComponent().toString());

             
                   }
       
    });      
            

   
             
    }  
   
 
      
   
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    }
   
    public static void main(String args[]) {
        setDefaultLookAndFeelDecorated(true);
             
        new gui2().show();
       
       
       
    }
   
   
   
}
0
 
girionisCommented:
Do you get any error messages?
0
 
vihar123Author Commented:
no error, its not entering into this thing......
0
 
girionisCommented:
What happens if you get rid of this line:

>  jTree1.getSelectionModel().setSelectionMode
>             (TreeSelectionModel.SINGLE_TREE_SELECTION);

0
 
CEHJCommented:
The only thing wrong with your code is that you have a window with no dimension and a tree control that has been added to nothing. Put these lines at the end of initComponents:

                  getContentPane().add(jTree1, java.awt.BorderLayout.CENTER);
                  setSize(300, 300);
0
 
vihar123Author Commented:
im able to display path properly, but actually i want to display other data from the db, could you please tell me how to do this, im having the below code that properly displays path but i want to display other data from db, when im using rset, its giving an error as cannot resolve rset.

---------------

jTree1.getSelectionModel().setSelectionMode
            (TreeSelectionModel.SINGLE_TREE_SELECTION);
   
          jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent evt) {
                                               
                         DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();                                                              
                                             
                                             
                          TreePath tp = evt.getPath();
                         
                          jTextField1.setText(tp.toString());
                           
                   
                         }
       
    });      
0
 
girionisCommented:
What is the "rset", where do you declare it?
0
 
vihar123Author Commented:
its the resultset that i declared in the try block, i was trying to retreive data from the db using this rset and casting it to string.
0
 
girionisCommented:
Declare the result set outside the try block if you want to use it somewhere else. Variable inside the try...catch block are local to the block.
0
 
vihar123Author Commented:
i have instantiated TreePath tp to get the path, what should i use to display data from DB
0
 
girionisCommented:
0
 
vihar123Author Commented:
Here im getting the last selected component ----> node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();                                                              
here im getting the path--------->      TreePath tp = evt.getPath();
                         
here im casting it to textfield---------->    jTextField1.setText(tp.toString());

i want to achieve, getting other data from db and displaying on the fields.

can anybody give me some examples how to go about it.......
0
 
girionisCommented:
Well my example above should show you how to do it. Only thing you need to do is to substitute the names of the nodes in the example with the data you are reading from the database.
0
 
vihar123Author Commented:
this examples is adding new nodes, but i want to display related data from db when a node is selected,

and also its not accepting the method insertNodeINto----> model.insertNodeInto(newNode, node, node.getChildCount());
0
 
girionisCommented:
> this examples is adding new nodes, but i want to display related data from db when a node is selected,

Where do you want to display this data?

You need to do a request upon selecting a node to the database and select the data based on the value you will get from the node.
0
 
vihar123Author Commented:
i think correct link has to be established in the third line, but im unable to....any help or advises:-)
                                                                                    |
TreePath tp = evt.getPath();                                           |  
                                                   V  
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp.getLastPathComponent().toString(rset.getString("emp_desig"));              
                       
jTextField1.setText(node.toString());
0
 
girionisCommented:
So what is the actual problem? Displaying the text to the text field or retrieing the data from the database... I am confused.
0
 
vihar123Author Commented:
retreiving from the database
0
 
vihar123Author Commented:
im facing problem in retreiving data from db, i think something has to be done in this below line.........

DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp.getLastPathComponent();


or can u tell me how it generally works, i shld do something to the treepath (tp) that it retreives data


                                  or

shld i work with jTree1 like below....

DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent()


0
 
girionisCommented:
You simply need to retrieve the value fo the node and then do a separate query to the database based on this value. What exactly is the problem, retrieving the value of the node or querying the database?
0
 
CEHJCommented:
As mentioned before, using a UserObject will give you more versatility. Include the db key field in the UserObject and you should be able to get related db info by using it in a query
0
 
vihar123Author Commented:
problem is both retreiving the value of the node and also querying the database

first of all its not accepting rset eventhough i declared it final, its saying as rset should be initialised....

now with the below code, im able to get the last component selected and display in the textfield.

in the second field, i want to retreive data from db, and i have no idea how to do it, i think thers some simple logic but im unable to find it.

an example might probably help me....
---------------------------------------------------------------------------------------

Connection conn;
       
       final Statement stmt;
       
       final ResultSet rset;
       
       
        try
        {
            DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
                     
           
            conn =
            DriverManager.getConnection ("................");
           
            stmt = conn.createStatement ();
                rset = stmt.executeQuery("select * from emp1");
           

           
                    while (rset.next())
               {
                              
                DefaultMutableTreeNode name1 = new DefaultMutableTreeNode(rset.getString("emp_name"));
              topnode.add(name1);
              DefaultMutableTreeNode salary = new DefaultMutableTreeNode(rset.getString("emp_sal"));
              name1.add(salary);
              DefaultMutableTreeNode commission = new DefaultMutableTreeNode(rset.getString("emp_comm"));
              salary.add(commission);
             

               }        
       
                         
                    jTree1.setRootVisible(true);
                    treeModel.reload();      
                   
                   
        }
                 
        catch (SQLException e)
        {
            System.out.println(e);
        }
       
 

    //jTree1.getSelectionModel().setSelectionMode
      //      (TreeSelectionModel.SINGLE_TREE_SELECTION);
   
          jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent evt) {
                                               
                                                                                                           
                        TreePath tp = evt.getNewLeadSelectionPath();
                   
                                 
                               jTextField1.setText(tp.toString());
                   
                         }
       
0
 
vihar123Author Commented:
>  using a UserObject will give you more versatility


when im using it, its giving the same error as i mentioned before, that rset should be initialized and cannot resolve symbol method user object located in default mutable tree node


node.userObject(rset.getString("emp_desig"));  
0
 
girionisCommented:
> first of all its not accepting rset eventhough i declared it final, its saying as rset should be initialised....

Initialize it to null: ResultSet rset = null;

Can you post the full code you have so far (hope it is not that big)?
0
 
CEHJCommented:
I don't quite understand what's happened - your code was working earlier, given the changes i mentioned (i know as i ran it myself)

>>node.userObject(rset.getString("emp_desig"));  

You're using the wrong method. It should be

http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/tree/DefaultMutableTreeNode.html#setUserObject(java.lang.Object)
0
 
vihar123Author Commented:
i think its small enough...........:-)

------------------------------------------------------------------------------
Connection conn;
       
       final Statement stmt;
       
       ResultSet rset = null;
       
       
        try
        {
            DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
                     
           
            conn =
            DriverManager.getConnection ("-----------");
           
            stmt = conn.createStatement ();
                rset = stmt.executeQuery("select * from emp1");
           

           
                    while (rset.next())
               {
                              
                DefaultMutableTreeNode name1 = new DefaultMutableTreeNode(rset.getString("emp_name"));
              topnode.add(name1);
              DefaultMutableTreeNode salary = new DefaultMutableTreeNode(rset.getString("emp_sal"));
              name1.add(salary);
              DefaultMutableTreeNode commission = new DefaultMutableTreeNode(rset.getString("emp_comm"));
              salary.add(commission);
             

               }        
       
                         
                    jTree1.setRootVisible(true);
                    treeModel.reload();      
                   
                   
        }
                 
        catch (SQLException e)
        {
            System.out.println(e);
        }
       
 

    //jTree1.getSelectionModel().setSelectionMode
      //      (TreeSelectionModel.SINGLE_TREE_SELECTION);
   
          jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent evt) {
                                               
                                               
                       //to show the last selected component
                         
        TreePath tp = evt.getNewLeadSelectionPath();
                   
       DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp.getLastPathComponent();
                               
                   jTextField1.setText(node.toString());
                               
                   
            //to retreive data from db and display
                               
             DefaultMutableTreeNode node1 = (DefaultMutableTreeNode) tp.getLastPathComponent();
                               
                   node1.getUserObject().(rset.getString("emp_desig"));
                               
                   jTextField2.setText(node1.toString());
                               
                                   
                            }
               
          }
       
        ---------*****im having problem in the above one, retreiving and displaying data***********************
       
    );      
0
 
girionisCommented:
Try first CEHJ's suggestion and if it does not work I will try to run it myself... I also remember it was running at some point.
0
 
vihar123Author Commented:
node1.setUserObject(rset.getString("emp_desig")); ----> is this method right, if so tell which method i shld use.
                               
jTextField2.setText(node1.toString());

when im doing like this, its giving me an error as rset shld be declared as final, but when im declaring it, i cannot do this ------------------> rset = stmt.executeQuery("select * from emp1");

its giving an error as cannot assign value to final variable.

its running till the tree path, and displaying also in the jtextfield1, but in the jtextfield2 i want to retreive data from db and display it.                               
0
 
girionisCommented:
>node1.getUserObject().(rset.getString("emp_desig"));
>                           
>                 jTextField2.setText(node1.toString());

If you just want to set the text of the node in the text field, simply do

jTextField2.setText(node1.toString());

get rid fo the first line: node1.getUserObject().(rset.getString("emp_desig"));

> its giving an error as cannot assign value to final variable.

Don't make it final.
0
 
vihar123Author Commented:
if i get rid of the first line where shld i retreive the data........

and with final as mentioned above

>>>when im doing like this, its giving me an error as rset shld be declared as final, but when im declaring it, i cannot do this ------------------> rset = stmt.executeQuery("select * from emp1");

its giving an error as cannot assign value to final variable.

0
 
girionisCommented:
Why do you need to declare your result set as final at first place?

> if i get rid of the first line where shld i retreive the data........

You already retrieve the data in the database code and you already create the tree.
0
 
vihar123Author Commented:
well is my question understandable, i have given the entire code above.

im retreiving data in the try and catch block and its running, but i want to display some data when user selects a node, so this i have to write in treeselectionlistener event, and here when im trying to use rset, its not accepting and giving error as local variable accessd within inner class, declare rset as final....but i cant do this cause i cannot give any values to final variable.

i think there lies some simple logic or the right method, that has to be given in the treeselectionlistener.

i wish i could get some snippets :)
0
 
girionisCommented:
>  but i want to display some data when user selects a node,

Do you want to display some data from the *same* query (ResultSet) or from a *different* one?
0
 
vihar123Author Commented:
or can somebody just give me an example or some links how to do this below thing.

imagine u have a tree control, when the user selects a node, it should retreive data from db and display it in the textfield.

0
 
vihar123Author Commented:
> Do you want to display some data from the *same* query (ResultSet) or from a *different* one?

from the same result set
if i want to do it with different, is it that i have to go through the whold try and catch process again.
0
 
girionisCommented:
Ok, there is a problem here... You cannot use the result set inside the try...catch block since it will be lockal to it. You can't also declare it final outside the try...catch block since you won't be able to assing another value to it. WHat I suggest is that you declare an instance variable called "emp_desig":

String emp_desig = null;

Inside your try...catch block set it to a value from the result set:

try
{
...
emp_desig = rset.getString("emp_desig");
}
catch
...
...

Inside you tree listener do the following:

 jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent evt) {
       TreePath tp = evt.getNewLeadSelectionPath();
      DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp.getLastPathComponent();
                 jTextField1.setText(node.toString());
           DefaultMutableTreeNode node1 = (DefaultMutableTreeNode) tp.getLastPathComponent();
                 node1.setUserObject(new String(emp_desig));
                 jTextField2.setText((String) node1.getUserObject());
                          }
               
         }
    );      
0
 
vihar123Author Commented:
ya i have tried it, and its giving the same things as string emp_desig shld be declared as final.
0
 
CEHJCommented:
>>Ok, there is a problem here... You cannot use the result set inside the try...catch block since it will be lockal to it.

Even if it were not a problem to use the same one, you probably wouldn't want to anyway, since i'm guessing that the query will be something like (pseudo)

select x from sometable where idField = <get id from user object> and otherfield = <get otherfield from user object>
0
 
girionisCommented:
Doh... You are right, you still access it from inside your inner class. Put the valuChanged method as a separate one and make your class to implement TreeSelectionListener. Then add your class to the jTree1. This should solve the problem.
0
 
girionisCommented:
Nope, CEHJ, vihar123 stated that he wants to use the same result set.
0
 
CEHJCommented:
>>vihar123 stated that he wants to use the same result set.

How and why - s/he has already displayed the result set?
0
 
girionisCommented:
Not sure why.
0
 
vihar123Author Commented:
this looks interesting.....can u inform me further how to do it with a new resultset

>>Ok, there is a problem here... You cannot use the result set inside the try...catch block since it will be lockal to it.

Even if it were not a problem to use the same one, you probably wouldn't want to anyway, since i'm guessing that the query will be something like (pseudo)

select x from sometable where idField = <get id from user object> and otherfield = <get otherfield from user object>
0
 
CEHJCommented:
>>can u inform me further how to do it with a new resultset

First of all, you'll have to tell *us* what you're trying to achieve - we don't want to be guessing ;-)
0
 
vihar123Author Commented:
i think new result set makes sense rather than changing the entire class structure.....could you please inform me more how to´go about with new result set.
0
 
CEHJCommented:
See last comment
0
 
vihar123Author Commented:
>>First of all, you'll have to tell *us* what you're trying to achieve - we don't want to be guessing ;-)

what all i want to achieve is that when user selects a node, it gets data from db and displays it in the textfield.

and i really have no idea to use same resultset ór different resultset, i thought using same resultset will make my code simple :-)
0
 
CEHJCommented:
>>what all i want to achieve is that when user selects a node, it gets data from db and displays it in the textfield.

Well that's not telling us much ;-)
0
 
vihar123Author Commented:
ok u can see from my above code, i have put a tree control and retreived nodes from the db. like given down

           while (rset.next())
               {
                             
               DefaultMutableTreeNode name1 = new DefaultMutableTreeNode(rset.getString("emp_name"));
              topnode.add(name1);
              DefaultMutableTreeNode salary = new DefaultMutableTreeNode(rset.getString("emp_sal"));
              name1.add(salary);
              DefaultMutableTreeNode commission = new DefaultMutableTreeNode(rset.getString("emp_comm"));
              salary.add(commission);              

               }      

its working well.... and now i want to display some more data on the textfields from the same table and also other table when the user selects a particular node, for eg:-

               emp_name
                       bob
                       john---
                                 |
                                 emp_sal
                                     2222---
                                                |
                                               emp_commission
                                                  50

so when user selects john, i want to get other information from db, say emp_age (from the same table or diff table) and display it in the jtextfield.

hope im telling much and clear :-)

               
                       
0
 
CEHJCommented:
>>hope im telling much and clear :-)

That's better ;-) I've actually already said how i'd do this:

>>
As mentioned before, using a UserObject will give you more versatility. Include the db key field in the UserObject and you should be able to get related db info by using it in a query
>>

So if the user clicks on john you'd do

select age from x where id = <john's id>. You need a class for the user object to encapsulate the id and other info

0
 
vihar123Author Commented:
i think its your turn now to explain much and clear :-)

>>
As mentioned before, using a UserObject will give you more versatility. Include the db key field in the UserObject and you should be able to get related db info by using it in a query
>>


***where should i use this user object - in try-catch block, then how it will get the event

****should i make a new resultset, if yes how

i think if resultset problem is solved, ie making a new result set, then itll be simpler....

0
 
vihar123Author Commented:
ok ill make the question simple, what is the way of making new resultset.
0
 
CEHJCommented:
OK - presumably you have a key field called something like 'emp_id'?
0
 
girionisCommented:
Just use the code you are using in the try...catch block (except the jtree code) and you should be ok. Do not forget to change the query and also close any result set, connectoin and statement objects after you are done.
0
 
vihar123Author Commented:
I tried using the same code but how to make it get the right information of the person. for eg:- when i click the name john it should get me his designation. presently it shows only the last field.
any suggestions please on how to get the related info. shld something be done in the query.....or is there some other way
--------------------

Connection conn2;
       
Statement stmt2;
       
ResultSet rset2 = null;
                                                              
try
{
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
                     
conn2 = DriverManager.getConnection (".......");
           
stmt2 = conn2.createStatement ();
rset2 = stmt2.executeQuery("select emp_desig from emp1");
                               
while (rset2.next())
 {
                              
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(rset2.getString("emp_desig"));
                          
node1.setUserObject(new String(rset2.getString("emp_desig")));                                    
jTextField2.setText((String) node1.getUserObject());

 }
                              
conn2.close();
stmt2.close();
rset2.close();

0
 
girionisCommented:
Your select statement is wrong. It should look like:

rset2 = stmt2.executeQuery("select * from emp1 WHERE emp_name = 'john'");

Where john would be a dynamic value that you will be passing upon selecting different names. Something like:

Statement stmt2;
       
ResultSet rset2 = null;
DefaultMutableTreeNode node1 = (DefaultMutableTreeNode) tp.getLastPathComponent();                 String empName = node1.toString();

try
{
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
                     
conn2 = DriverManager.getConnection (".......");
           
stmt2 = conn2.createStatement ();
rset2 = stmt2.executeQuery("select * from emp1 WHERE emp_name = '" + empName + "'");
                           
while (rset2.next())
{
    jTextField2.setText(rs2,getString("<column you want here>");
}
                         
conn2.close();
stmt2.close();
rset2.close();

You do not need to be selecting nodes again inside your while loop. The while loop should only be dealing with the result set. You already select the node you want and use its value to construct the query.
0
 
CEHJCommented:
>>when i click the name john it should get me his designation.

Then the following

>>rset2 = stmt2.executeQuery("select * from emp1 WHERE emp_name = 'john'");

is not really what you need. What happens if there is more than one employee called John?
You need to use the id field

0
 
vihar123Author Commented:
Thanks girionis
0
 
CEHJCommented:
vihar123, can you tell me why you completely ignored my extensive contribution to this long question when it came to points allocation?
0
 
vihar123Author Commented:
oops sorry i forgot to split points.....can u tell me how can i change it now

extremely sorry :-)
0
 
girionisCommented:
Ask a question to community support for zero points to reopen the question: http://www.experts-exchange.com/Community_Support/ Or post here and venabili might be able to do it for you: http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21100047.html
0
 
CEHJCommented:
;-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 35
  • 31
  • 27
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now