Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Editing a leaf in JTree and updating changes to database 1

Status
Not open for further replies.

pjeypal

Programmer
Apr 17, 2006
36
US
Hi,

I have a dynamic JTree built from records in an oracle database.I created the tree with two fields location and description displayed side by side on the tree, something like this :

Root
|
location :: description
.
.
location4000 :: description4000

I want the description field to be editable and the changes made should be updated to the database in the description field
I have done the coding to make the cell editable
But since both fields are displyed side by side and are part of single leaf both becomes editable.Is there anyway to make just description editable

I'm adding the entire code for the screen below

Any help on this appreciated.

import javax.swing.*;

import java.awt.*;
import javax.swing.border.*;
import javax.swing.tree.*;
import java.sql.*;



class MyNode extends DefaultMutableTreeNode
{
private String location;

public MyNode(String location){
this.location=location;
}
public String toString(){
return location;
}

}
public class HierarchyTool extends JFrame
{
private Container container;
private JMenu file,action;
private JPanel statusPanel,toolPanel,treePanel,filterPanel,dataPanel;
private JComboBox drawingCmb,ex01Cmb,ex02Cmb;
private JButton dataButton,clearButton;
private JTree jtree,jtree1;
String result=null;
DefaultMutableTreeNode root=new DefaultMutableTreeNode();
DefaultMutableTreeNode root1=new DefaultMutableTreeNode();

HierarchyTool()
{
super("HierarchyTool");
LoginScreen loginScreen=new LoginScreen(this);
container=getContentPane();
container.setLayout(new BorderLayout());

JMenuBar mBar=new JMenuBar();
file=new JMenu("File");
JMenuItem exit=new JMenuItem("Exit");
file.add(exit);
mBar.add(file);

action=new JMenu("Action");
JMenuItem impexp=new JMenuItem("Import/Export");
action.add(impexp);
JMenuItem clear=new JMenuItem("Clear Hierarchy");
action.add(clear);
mBar.add(action);

setJMenuBar(mBar);

toolPanel=new JPanel();
toolPanel.setLayout(new GridLayout(1,2));


filterPanel=new JPanel();
filterPanel.setLayout(new GridLayout(2,3,15,5));

drawingCmb=new JComboBox(new Object[]{"Search Field"});
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con3=DriverManager.getConnection("jdbc:eek:dbc:htool","scott","tiger");
Statement st3=con3.createStatement();
ResultSet rs3=st3.executeQuery("select distinct(drawing) from buildhierarchy");



while(rs3.next()){
drawingCmb.addItem(rs3.getString("drawing"));
}
}

catch(Exception e){}
JLabel lab=new JLabel("Drawing");

filterPanel.add(lab);

lab=new JLabel("EX01");
filterPanel.add(lab);

lab=new JLabel("EX02");
filterPanel.add(lab);

drawingCmb.setSize(80,20);
filterPanel.add(drawingCmb);

ex01Cmb=new JComboBox(new Object[]{"Search Field#2"});
try{

Connection con1=DriverManager.getConnection("jdbc:eek:dbc:htool","scott","tiger");
Statement st1=con1.createStatement();
ResultSet rs1=st1.executeQuery("select distinct(ex01) from buildhierarchy");



while(rs1.next()){
ex01Cmb.addItem(rs1.getString("ex01"));
}
}

catch(Exception e){}
filterPanel.add(ex01Cmb);
ex02Cmb=new JComboBox(new Object[]{"Search Field#3"});
try{

Connection con2=DriverManager.getConnection("jdbc:eek:dbc:htool","scott","tiger");
Statement st2=con2.createStatement();
ResultSet rs2=st2.executeQuery("select distinct(ex02) from buildhierarchy");



while(rs2.next()){
ex02Cmb.addItem(rs2.getString("ex02"));
}
}

catch(Exception e){}
filterPanel.add(ex02Cmb);

filterPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),"Filter"));
toolPanel.add(filterPanel);

dataPanel=new JPanel();
dataPanel.setLayout(new FlowLayout(FlowLayout.CENTER,50,10));
dataButton=new JButton(new ImageIcon("excel.jpg"));

dataPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),"Data"));

clearButton=new JButton(new ImageIcon("clear.jpg"));

dataPanel.add(dataButton);
dataPanel.add(clearButton);
toolPanel.add(dataPanel);

container.add(toolPanel,BorderLayout.NORTH);

try{

Connection con=DriverManager.getConnection("jdbc:eek:dbc:htool","scott","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select location,description from buildhierarchy");
ResultSetMetaData rsmd=rs.getMetaData();


while(rs.next()){
result=""+rs.getString("location")+" :: "+rs.getString("description");
DefaultMutableTreeNode mtn=new MyNode(result);
root.add(mtn);
}
}

catch(Exception e){}

jtree=new JTree(root);
jtree.setEditable(true);
DefaultTreeCellRenderer renderer=(DefaultTreeCellRenderer)jtree.getCellRenderer();
TreeCellEditor editor= new LeafCellEditor(jtree,renderer);
jtree.setCellEditor(editor);

jtree1=new JTree(root1);

JScrollPane leftPane=new JScrollPane(jtree);
JScrollPane rightPane=new JScrollPane(jtree1);

JSplitPane splitPane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,leftPane,rightPane);
splitPane.setBackground(Color.white);
splitPane.setDividerLocation(390);
container.add(splitPane,BorderLayout.CENTER);

statusPanel=new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel statusLab=new JLabel("",JLabel.LEFT);
statusLab.setOpaque(true);
statusLab.setText("Status");
statusPanel.add(statusLab);

//statusPanel.setBorder(BorderFactory.createLineBorder(Color.black));
container.add(statusPanel,BorderLayout.SOUTH);
setTitle("HierarchyTool");
setSize(800,584);
show();
}

/*private DefaultMutableTreeNode processHierarchy(Object[] hierarchy){
DefaultMutableTreeNode node=
new DefaultMutableTreeNode(hierarchy[0]);
DefaultMutableTreeNode child;
for(int i=1;i<hierarchy.length;i++){
Object nodeSpecifier=hierarchy;
if(nodeSpecifier instanceof Object[])
child=processHierarchy((Object[])nodeSpecifier);
else
child=new DefaultMutableTreeNode(nodeSpecifier);
node.add(child);
}
return(node);
}*/

class LeafCellEditor extends DefaultTreeCellEditor {

public LeafCellEditor(JTree jtree, DefaultTreeCellRenderer renderer) {
super(jtree, renderer);
}

public LeafCellEditor(JTree jtree, DefaultTreeCellRenderer renderer,
TreeCellEditor editor) {
super(jtree, renderer, editor);
}

public boolean isCellEditable(EventObject event) {
// Get initial setting
boolean returnValue = super.isCellEditable(event);
// If still possible, check if current tree node is a leaf
if (returnValue) {
Object node = jtree.getLastSelectedPathComponent();
if ((node != null) && (node instanceof TreeNode)) {
TreeNode treeNode = (TreeNode) node;
returnValue = treeNode.isLeaf();
}
}
return returnValue;
}
}
public static void main(String args[])
{
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch(Exception e){
}
new HierarchyTool();
}
}

Thanks,
Priya


 
Why use the JdbcOdbcDriver to connect to Oracle ? It is not a stable driver, and also will be a lot slower than using Oracle's driver oracle.jdbc.driver.OracleDriver .

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
It will be implemented later using difffernt driver.any ideas on how to go about this?
 
Code:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection c = DriverManager.getConnection("jdbc:oracle:thin:@hostname:1521:SID", "user", "passwd");

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Hi,
Thanks for the tip about connection.I urgently need the other problem about editing of nodes to be solved.Any suggestions for the same?

Regards,
Priya

 
Who showed you this:
Code:
        catch(Exception e){}
fire drencher

Never, never, never do this.
It's like installing an empty fire drencher and labelling it 'Full. Last check: today'.

I'm in hurry - perhaps I find the answer to your question later.

seeking a job as java-programmer in Berlin:
 
Did you read the 'How to use Trees'-Tutorial, mentioned and linked on top of the api-doc page for JTree?

Here we have a very mediocre idea:
Code:
     result=""+rs.getString("location")+" :: "+rs.getString("description");
            DefaultMutableTreeNode mtn=new MyNode(result);
You merge two Strings together, but later you like to modify just one of them, so you have to split them.

Here is a fast idea to modify your code, but I guess you'll find much better ideas by reading the tutorial:
Code:
 class MyNode extends DefaultMutableTreeNode 
{
	private String location;
	private String description;
		
	private JTextField jtf;
	private JLabel jlabel;
	private JPanel jp;
		
	public MyNode (String location, String description)
	{
		this.location = location;
		this.description = description;
		jlabel = new JLabel (location);
		jtf = new JTextField (description);
		jp = new JPanel ();
		jp.setLayout (new BoxLayout (jp, BoxLayout.LINE_AXIS));
		jp.add (jlabel);
		jp.add (jtf);		
	}

	public String toString ()
	{
		return location + "::" + description;
	}
	
	public JComponent getAsJComponent ()
	{
		return jp;
	}
	
	public void getValuesAfterEdit ()
	{
		String desc = jtf.getText ();
		description = desc;
	}
	
	public String getDescription ()
	{
		return description;
	}
}
You keep both parts of the node separat, and return the merged form just in 'toString ()'.

Why the other methods?
Well look at this:
Code:
 class MyDualCellTreeRenderer extends DefaultTreeCellRenderer // implements TreeCellRenderer
	{
		public JComponent getTreeCellRendererComponent (JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) 
		{
			System.out.println ("renderer called! " + value.toString ());			
			if (value instanceof MyNode)
			{
				MyNode mn = (MyNode) value;
				return mn.getAsJComponent ();
			}
			return new JLabel ("root");
		}
	}
I guess the getAsJComponent now is pretty clear.

But what's about the getValuesAfterEdit-method?
Code:
 class DualLeafCellEditor extends DefaultTreeCellEditor 
	{
		private MyNode mn;
			
		public DualLeafCellEditor (JTree jtree, DefaultTreeCellRenderer renderer) 
		{
			super (jtree, renderer);
		}
		
		public Component getTreeCellEditorComponent (JTree tree,
						    Object value,
						    boolean isSelected,
						    boolean expanded,
						    boolean leaf,
						    int row)
		{
			System.out.println ("editor called! " + value.toString ());			
			if (value instanceof MyNode)
			{
				mn = (MyNode) value;
				return mn.getAsJComponent ();
			}
			return new JLabel ("root");
		}
		
		public void cancelCellEditing ()
		{
			System.out.println ("editor cancel cell edit! ");			
			mn.getValuesAfterEdit ();
		}
		
		public boolean stopCellEditing () 
		{
			System.out.println ("editor stop cell edit! ");			
			mn.getValuesAfterEdit ();
			return true;
		}
		
		public boolean isCellEditable (java.util.EventObject eo) 
		{
			return true;
		}
	}

I'm not feeling very well with this hack.
I don't like the extension of the DefaultTreeCellRenderer (DTRC).
But the DefaultTreeCellEditor doesn't accept a TreeCellRender (which is an interface, and would fit to my expections), but only a DTRC.
The DTRC extends a JLable.
Since I like to extend from JPanel (to layout multiple elements) I should add a Panel to the JLabel (which seems possible - never done that) and add the subcomponents to the JPanel... ?

Perhaps a cleaner solution is possible by using a TableModel.

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top