Hai

I am in need of add a JCheckbox as a node in JTree components, how can i do this

herewith i have paste my code for your consideration

Please help me

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import java.sql.ResultSet;
import javax.swing.AbstractCellEditor;
import javax.swing.DefaultCellEditor;
import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.text.Position;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.JDialog;
import javax.swing.JPanel;
import java.awt.GridBagLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.io.File;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JSplitPane;



import java.awt.event.ActionListener;
import java.awt.font.FontRenderContext;
public class UserPermission extends JDialog implements ActionListener,TreeSelectionListener
{

/**
*
*/
private static final long serialVersionUID = 1L;
private ResultSet rs =null; // @jve:decl-index=0:
private JPanel panMain = null; // @jve:decl-index=0:visual-constraint="15,62"
//private JTree jTree = null;
private CheckBoxTree jTree = null;
private DefaultMutableTreeNode top = null;
private DefaultMutableTreeNode node=null; // @jve:decl-index=0:
protected DefaultTreeModel m_model=null;
protected JCheckBox chk = new JCheckBox("");
private JButton jButton = null;
private JButton btnCancel = null;
private JScrollPane jScrollPane = null; // @jve:decl-index=0:visual-constraint="582,197"
private JSplitPane jSplitPane = null; // @jve:decl-index=0:visual-constraint="569,269"
private JScrollPane empScrollPane = null; // @jve:decl-index=0:visual-constraint="620,91"
private JTree treeEmp = null;
private String nodeName=null;
private String menuName=null;
private String usrId="";
private ArrayList selectedMenu=new ArrayList(); // @jve:decl-index=0:
public UserPermission(JFrame obj)
{
super(obj,"User Permission",true);
add(getPanMain());
}

public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
treeEmp.getLastSelectedPathComponent();


if (node == null ) return;
Object nodeInfo = node.getUserObject();
nodeName=nodeInfo.toString();
getUserId();
getUserPermission();


}
public TreePath[] getPaths(JTree tree, boolean expanded) {
TreeNode root = (TreeNode)tree.getModel().getRoot();

// Create array to hold the treepaths
List list = new ArrayList();

// Traverse tree from root adding treepaths for all nodes to list
getPaths(tree, new TreePath(root), expanded, list);

// Convert list to array
return (TreePath[])list.toArray(new TreePath[list.size()]);
}

public void getPaths(JTree tree, TreePath parent, boolean expanded, List list) {
// Return if node is not expanded
if (expanded && !tree.isVisible(parent)) {
return;
}

// Add node to list
list.add(parent);

// Create paths for all children
TreeNode node = (TreeNode)parent.getLastPathComponent();
if (node.getChildCount() >= 0) {
for (Enumeration e=node.children(); e.hasMoreElements(); ) {
TreeNode n = (TreeNode)e.nextElement();

TreePath path = parent.pathByAddingChild(n);

getPaths(tree, path, expanded, list);
}
}
}

public void actionPerformed(ActionEvent ae)
{
try
{
if(ae.getSource()==jButton)
{
selectedMenu.clear();
TreePath[] path= getPaths(jTree, false);
String name="";
for(int i=0;i<path.length;i++)
{
if(path[i].toString().indexOf("true")>0)
{
JOptionPane.showMessageDialog(null,path[i].toString());
name=path[i].toString().substring(path[i].toString().lastIndexOf("[")+1,path[i].toString().lastIndexOf("/"));
selectedMenu.add(String.valueOf(name));
}
}
if(selectedMenu.size()<1)
{
JOptionPane.showMessageDialog(null,"There is no changes to update!");
dispose();
}
else
{
usrId="";
getUserId();

if(usrId.trim().length()==0)
return;
String sql="select count(*) as cnt from user_permission where um_id='"+usrId+"'";
rs=Global.nlaDbase.getRecordSet(sql);
boolean exist=false;
if(rs.next())
{
if(Integer.parseInt(rs.getString("cnt"))>0)
exist=true;
else
exist=false;
}
rs.close();
if(exist)
Global.nlaDbase.Update("delete from user_permission where um_id='"+usrId+"'");
String menuId="",menuSub="";
for(int i=0;i<selectedMenu.size();i++)
{
sql="select mm_id,mm_submenu from menu_master where mm_menuname='"+String.valueOf(selectedMenu.get(i)) +"'";
rs=Global.nlaDbase.getRecordSet(sql);
if(rs.next())
{
menuId=rs.getString("mm_id");
menuSub=rs.getString("mm_submenu");
}
rs.close();


Global.nlaDbase.Update("insert into user_permission (um_id,mm_id,mm_menuname,mm_submenu) values ('"+usrId+"','"+menuId+"','"+String.valueOf(select edMenu.get(i))+"','"+menuSub+"')");
}
JOptionPane.showMessageDialog(null,"The Permission(s) has been updated");
dispose();
}
}
else if(ae.getSource()==btnCancel)
{
dispose();




}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.toString());
ex.printStackTrace();
}
}
private void getUserId()
{
try
{
String sql="select um_id from usermaster where um_name='"+nodeName+"'";
rs=Global.nlaDbase.getRecordSet(sql);
if(rs.next())
{
usrId=rs.getString("um_id");
}
rs.close();
if(usrId.trim().length()==0)
return;
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.toString());
ex.printStackTrace();
}
}
private void getUserPermission()
{
Vector v=new Vector();
try
{
rs.close();
//JOptionPane.showMessageDialog(null,usrId);
rs=Global.nlaDbase.getRecordSet("select * from user_permission where um_id='"+usrId+"'");
while(rs.next())
{
v.add(rs.getString("mm_menuname"));

}

rs.close();

/*TreeNode root = (TreeNode)jTree.getModel().getRoot();
TreePath parent=new TreePath(root);
TreeNode node = (TreeNode)parent.getLastPathComponent();
if (node.getChildCount() >= 0) {
for (Enumeration e=node.children(); e.hasMoreElements(); )
{
TreeNode n = (TreeNode)e.nextElement();

TreePath path = parent.pathByAddingChild(n);



//JOptionPane.showMessageDialog(null,"Called :"+path.toString());
}
}*/




for(int i=0;i<v.size();i++)
{
TreePath p = findByName(jTree, new String[]{"M"});
//if(p!= null)
JOptionPane.showMessageDialog(null," Inside For"+p.toString());

}

}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.toString());
ex.printStackTrace();
}
}

public TreePath findByName(JTree tree, String[] names) {
TreeNode root = (TreeNode)tree.getModel().getRoot();
JOptionPane.showMessageDialog(null,"Inside findByName ");
return find2(tree, new TreePath(root), names, 0, true);
}

private TreePath find2(JTree tree, TreePath parent, Object[] nodes, int depth, boolean byName)
{
try
{
TreeNode node = (TreeNode)parent.getLastPathComponent();
Object o = node;
// If by name, convert node to a string
if (byName) {
o = o.toString();
}

JOptionPane.showMessageDialog(null,"Test");

// If equal, go down the branch
if (o.equals(nodes[depth])) {
// If at end, return match
if (depth == nodes.length-1) {
return parent;
}

// Traverse children
if (node.getChildCount() >= 0) {
for (Enumeration e=node.children(); e.hasMoreElements(); ) {
TreeNode n = (TreeNode)e.nextElement();
TreePath path = parent.pathByAddingChild(n);
for(int x=0;x<nodes.length;x++)
JOptionPane.showMessageDialog(null," Given String to Find "+String.valueOf(nodes[x]));
TreePath result = find2(tree, path, nodes, depth+1, byName);
// Found a match
if (result != null) {
return result;
}
}
}
}

// No match at this branch
return null;
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Inside : "+ex.toString());
ex.printStackTrace();
return null;
}
}


/**
* This method initializes panMain
*
* @return javax.swing.JPanel
*/
private JPanel getPanMain() {
if (panMain == null) {
panMain = new JPanel();
panMain.setLayout(null);
//panMain.setSize(new Dimension(445, 465));
panMain.setSize(new Dimension(445, 470));
panMain.add(getJTree(), null);
panMain.add(getJButton(), null);
panMain.add(getBtnCancel(), null);
panMain.add(getJSplitPane(),null);
}
return panMain;
}

private void expand(JTree tree) {
DefaultMutableTreeNode root =
(DefaultMutableTreeNode)tree.getModel().getRoot();
java.util.Enumeration e = root.breadthFirstEnumeration();
while(e.hasMoreElements()) {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode)e.nextElement();
if(node.isLeaf()) continue;
int row = tree.getRowForPath(new TreePath(node.getPath()));
tree.expandRow(row);
}
}


private JTree getJTree() {
if (jTree == null)
{
try
{
setNode();
expand(jTree);
CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();
jTree.setCellRenderer(renderer);


jTree.setCellEditor(new CheckBoxNodeEditor(jTree));

jTree.setEditable(true);
jTree.putClientProperty("JTree.lineStyle", "Angled");

jTree.setShowsRootHandles(true);
jTree.addTreeSelectionListener(this);

}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.toString());
ex.printStackTrace();
}


}
return jTree;
}

/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton();
//jButton.setBounds(new Rectangle(283, 436, 74, 20));
jButton.setBounds(new Rectangle(283, 470, 74, 20));
jButton.setText("Update");
jButton.addActionListener(this);
}
return jButton;
}



/**
* This method initializes btnCancel
*
* @return javax.swing.JButton
*/
private JButton getBtnCancel() {
if (btnCancel == null) {
btnCancel = new JButton();
//btnCancel.setBounds(new Rectangle(365, 436, 74, 20));
btnCancel.setBounds(new Rectangle(365, 470, 74, 20));
btnCancel.setText("Cancel");
btnCancel.addActionListener(this);
}
return btnCancel;
}



/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane(jTree,JScrollPane.VERTICAL_SCROLLBAR_A LWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane.setBounds(90, 51, 483, 301);
}
return jScrollPane;
}



/**
* This method initializes jSplitPane
*
* @return javax.swing.JSplitPane
*/
private JSplitPane getJSplitPane() {
if (jSplitPane == null) {
jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
jSplitPane.setTopComponent(getEmpScrollPane());
jSplitPane.setBottomComponent(getJScrollPane());
jSplitPane.setSize(new Dimension(450, 450));
jSplitPane.setDividerLocation(100);
}
return jSplitPane;
}



/**
* This method initializes empScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getEmpScrollPane() {
if (empScrollPane == null) {
empScrollPane = new JScrollPane();
empScrollPane.setSize(new Dimension(245, 250));
empScrollPane.setViewportView(getTreeEmp());
}
return empScrollPane;
}



/**
* This method initializes treeEmp
*
* @return javax.swing.JTree
*/
private JTree getTreeEmp() {
if (treeEmp == null) {

try
{

DefaultMutableTreeNode top =
new DefaultMutableTreeNode("User List");

rs=Global.nlaDbase.getRecordSet("select um_name as name from usermaster where um_id <>md5('admin')");
while(rs.next())
{
top.add(new DefaultMutableTreeNode(rs.getString("name")));
}
treeEmp = new JTree(top);


rs.close();

treeEmp.setEditable(false);
treeEmp.putClientProperty("JTree.lineStyle", "Angled");

treeEmp.setShowsRootHandles(true);
treeEmp.addTreeSelectionListener(this);


}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.toString());
ex.printStackTrace();
}


}
return treeEmp;
}


protected void setNode()
{
try
{
String sl="SELECT * FROM menu_master where length(trim(mm_submenu))=0 and mm_menutype='main'";
ArrayList mainMenu=new ArrayList();
ArrayList subMenu=new ArrayList();
ArrayList vect=new ArrayList();
ArrayList master=new ArrayList();

Vector rootVector=new Vector();
Vector accessVector=new Vector();
rs=Global.nlaDbase.getRecordSet(sl);
while(rs.next())
{
mainMenu.add(String.valueOf(rs.getString("MM_Menun ame")));
}
rs.close();
for(int i=0;i<mainMenu.size();i++)
{

sl="SELECT * FROM menu_master where mm_submenu='"+mainMenu.get(i)+"' and mm_menutype='Sub'";
rs=Global.nlaDbase.getRecordSet(sl);
while(rs.next())
{
subMenu.add(String.valueOf(rs.getString("MM_Menuna me")));
}
rs.close();
for(int j=0;j<subMenu.size();j++)
{
master.add(new CheckBoxNode(String.valueOf(subMenu.get(j)), false));
}

vect.add(new NamedVector(String.valueOf(mainMenu.get(i)),master ));

subMenu.clear();
accessVector.clear();
master.clear();
}
mainMenu.clear();
rootVector.add(new NamedVector("Root", vect));
//jTree = new JTree(rootVector);
jTree = new CheckBoxTree(rootVector);

rootVector.clear();
vect.clear();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.toString());
ex.printStackTrace();
}
}

}
class CheckBoxNode
{
String text;

boolean selected;

public CheckBoxNode(String text, boolean selected) {
this.text = text;
this.selected = selected;
}

public boolean isSelected() {
return selected;
}

public void setSelected(boolean newValue) {
selected = newValue;
}

public String getText() {
return text;
}

public void setText(String newValue) {
text = newValue;
}

public String toString() {
return getClass().getName() + "[" + text + "/" + selected + "]";
}
}

class NamedVector extends Vector {
String name;

public NamedVector(String name) {
this.name = name;
}

public NamedVector(String name, Object elements[])
{
this.name = name;
/*for (int i = 0, n = elements.length; i < n; i++) {
add(elements[i]);
}*/
}

public NamedVector(String name, ArrayList elements)
{
this.name = name;
for (int i = 0, n = elements.size(); i < n; i++) {
add(elements.get(i));
}
}


public String toString() {
return "[" + name + "]";
}
}

class CheckBoxNodeEditor extends AbstractCellEditor implements TreeCellEditor {

CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();

protected transient int offset;
protected int clickCountToStart = 1;

ChangeEvent changeEvent = null;

JTree tree;

public CheckBoxNodeEditor(JTree tree) {
this.tree = tree;
}

public Object getCellEditorValue() {
JCheckBox checkbox = renderer.getLeafRenderer();
CheckBoxNode checkBoxNode = new CheckBoxNode(checkbox.getText(),
checkbox.isSelected());
return checkBoxNode;
}

public boolean isCellEditable(EventObject event)
{
boolean returnValue = false;
if (event instanceof MouseEvent) {
MouseEvent mouseEvent = (MouseEvent) event;
TreePath path = tree.getPathForLocation(mouseEvent.getX(),
mouseEvent.getY());
if (path != null) {
Object node = path.getLastPathComponent();
if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
Object userObject = treeNode.getUserObject();
returnValue = ((treeNode.isLeaf()) && (userObject instanceof CheckBoxNode));
}
}
}
return returnValue;


}



public Component getTreeCellEditorComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row) {

Component editor = renderer.getTreeCellRendererComponent(tree, value,
true, expanded, leaf, row, true);

// editor always selected / focused
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
if (stopCellEditing()) {
fireEditingStopped();
}
}
};
if (editor instanceof JCheckBox) {
((JCheckBox) editor).addItemListener(itemListener);
}

return editor;
}
}

class CheckBoxNodeRenderer implements TreeCellRenderer {
private JCheckBox leafRenderer = new JCheckBox();

private DefaultTreeCellRenderer nonLeafRenderer = new DefaultTreeCellRenderer();

Color selectionBorderColor, selectionForeground, selectionBackground,
textForeground, textBackground;

protected JCheckBox getLeafRenderer() {

return leafRenderer;
}

public CheckBoxNodeRenderer() {
Font fontValue;
fontValue = UIManager.getFont("Tree.font");
if (fontValue != null) {
leafRenderer.setFont(fontValue);
}
Boolean booleanValue = (Boolean) UIManager
.get("Tree.drawsFocusBorderAroundIcon");
leafRenderer.setFocusPainted((booleanValue != null)
&& (booleanValue.booleanValue()));


selectionBorderColor = UIManager.getColor("Tree.selectionBorderColor");
selectionForeground = UIManager.getColor("Tree.selectionForeground");
selectionBackground = UIManager.getColor("Tree.selectionBackground");
textForeground = UIManager.getColor("Tree.textForeground");
textBackground = UIManager.getColor("Tree.textBackground");
}

public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {

Component returnValue;
if (leaf) {

String stringValue = tree.convertValueToText(value, selected,
expanded, leaf, row, false);
leafRenderer.setText(stringValue);
leafRenderer.setSelected(false);

leafRenderer.setEnabled(tree.isEnabled());

/* if (selected) {
leafRenderer.setForeground(selectionForeground);
leafRenderer.setBackground(selectionBackground);
} else {
leafRenderer.setForeground(textForeground);
leafRenderer.setBackground(textBackground);
}*/

if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
Object userObject = ((DefaultMutableTreeNode) value)
.getUserObject();
if (userObject instanceof CheckBoxNode) {
CheckBoxNode node = (CheckBoxNode) userObject;
leafRenderer.setText(node.getText());
leafRenderer.setSelected(node.isSelected());
}
}
returnValue = leafRenderer;
} else {
returnValue = nonLeafRenderer.getTreeCellRendererComponent(tree,
value, selected, expanded, leaf, row, hasFocus);
}
return returnValue;
}
}