Checkbox n jtree

hi all.... i wan new in swing
how can i add check box in each node of my jtree?
tis r my full program..... pls help me... tz..........very much
//FileTreePanel.java
package com.y
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import com.y.FileSystemModel;
public class FileTreePanel extends JPanel {
private JTree fileTree;
private FileSystemModel fileSystemModel;
private JTextArea fileDetailsTextArea;
public FileTreePanel( String directory )
fileDetailsTextArea = new JTextArea();
fileDetailsTextArea.setEditable( false );
fileSystemModel = new FileSystemModel(
new File( directory ) );
fileTree = new JTree( fileSystemModel );
fileTree.setEditable( true );
fileTree.addTreeSelectionListener(
new TreeSelectionListener() {
public void valueChanged(
TreeSelectionEvent event )
File file = ( File )
fileTree.getLastSelectedPathComponent();
fileDetailsTextArea.setText(
getFileDetails( file ) );
JSplitPane splitPane = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT, true,
new JScrollPane( fileTree ),
new JScrollPane( fileDetailsTextArea ) );
setLayout( new BorderLayout() );
add( splitPane );
} // end FileTreePanel constructor
public Dimension getPreferredSize()
return new Dimension( 400, 200 );
private String getFileDetails( File file )
// do not return details for null Files
if ( file == null )
return "";
StringBuffer buffer = new StringBuffer();
buffer.append( "Name: " + file.getName() + "\n" );
buffer.append( "Path: " + file.getPath() + "\n" );
buffer.append( "Size: " + file.length() + "\n" );
return buffer.toString();
public static void main( String args[] )
if ( args.length != 1 )
System.err.println(
"Usage: java FileTreeFrame <path>" );
else {
JFrame frame = new JFrame( "JTree FileSystem Viewer" );
FileTreePanel treePanel = new FileTreePanel( args[ 0 ] );
frame.getContentPane().add( treePanel );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
} // end method main
// FileSystemModel.java
package com.y;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
public class FileSystemModel implements TreeModel {
private File root;
private Vector listeners = new Vector();
public FileSystemModel( File rootDirectory )
root = rootDirectory;
// get hierarchy root (root directory)
public Object getRoot()
return root;
public Object getChild( Object parent, int index )
File directory = ( File ) parent;
String[] children = directory.list();
return new TreeFile( directory, children[ index ] );
public int getChildCount( Object parent )
// get parent File object
File file = ( File ) parent;
// get number of files in directory
if ( file.isDirectory() ) {
String[] fileList = file.list();
if ( fileList != null )
return file.list().length;
return 0; // childCount is 0 for files
// return true if node is a file, false if it is a directory
public boolean isLeaf( Object node )
File file = ( File ) node;
return file.isFile();
// get numeric index of given child node
public int getIndexOfChild( Object parent, Object child )
// get parent File object
File directory = ( File ) parent;
// get child File object
File file = ( File ) child;
// get File list in directory
String[] children = directory.list();
// search File list for given child
for ( int i = 0; i < children.length; i++ ) {
if ( file.getName().equals( children[ i ] ) ) {
// return matching File's index
return i;
return -1; // indicate child index not found
} // end method getIndexOfChild
// invoked by delegate if value of Object at given
// TreePath changes
public void valueForPathChanged( TreePath path,
Object value )
// get File object that was changed
File oldFile = ( File ) path.getLastPathComponent();
// get parent directory of changed File
String fileParentPath = oldFile.getParent();
// get value of newFileName entered by user
String newFileName = ( String ) value;
// create File object with newFileName for
// renaming oldFile
File targetFile = new File(
fileParentPath, newFileName );
// rename oldFile to targetFile
oldFile.renameTo( targetFile );
// get File object for parent directory
File parent = new File( fileParentPath );
// create int array for renamed File's index
int[] changedChildrenIndices =
{ getIndexOfChild( parent, targetFile) };
// create Object array containing only renamed File
Object[] changedChildren = { targetFile };
// notify TreeModelListeners of node change
fireTreeNodesChanged( path.getParentPath(),
changedChildrenIndices, changedChildren );
} // end method valueForPathChanged
// notify TreeModelListeners that children of parent at
// given TreePath with given indices were changed
private void fireTreeNodesChanged( TreePath parentPath,
int[] indices, Object[] children )
// create TreeModelEvent to indicate node change
TreeModelEvent event = new TreeModelEvent( this,
parentPath, indices, children );
Iterator iterator = listeners.iterator();
TreeModelListener listener = null;
// send TreeModelEvent to each listener
while ( iterator.hasNext() ) {
listener = ( TreeModelListener ) iterator.next();
listener.treeNodesChanged( event );
} // end method fireTreeNodesChanged
// add given TreeModelListener
public void addTreeModelListener(
TreeModelListener listener )
listeners.add( listener );
// remove given TreeModelListener
public void removeTreeModelListener(
TreeModelListener listener )
listeners.remove( listener );
// TreeFile is a File subclass that overrides method
// toString to return only the File name.
private class TreeFile extends File {
// TreeFile constructor
public TreeFile( File parent, String child )
super( parent, child );
public String toString()
return getName();
}

Also, use code tags and post a SSCCE -- I'm sure more of your posted code is irrelevant to your question and few people are going to look at a code listing that long.
[http://mindprod.com/jgloss/sscce.html]

Similar Messages

  • Checkbox with JTree

    hai,
    i added checkbox to each tree node and my coding is
    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.ComponentOrientation;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.InputEvent;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.AbstractAction;
    import javax.swing.AbstractButton;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.KeyStroke;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.TreeCellRenderer;
    import javax.swing.tree.TreePath;
    /** Provides checkbox-based selection of tree nodes. Override the protected
    * methods to adapt this renderer's behavior to your local tree table flavor.
    * No change listener notifications are provided.
    public class CheckBoxTreeCellRenderer implements TreeCellRenderer {
    public static final int UNSELECTABLE = 0;
    public static final int FULLSELECTED = 1;
    public static final int NOTSELECTED = 2;
    public static final int PARTIALSELECTED = 3;
    private TreeCellRenderer renderer;
    public static JCheckBox checkBox;
    private Point mouseLocation;
    private int mouseRow = -1;
    private int pressedRow = -1;
    private boolean mouseInCheck;
    private int state = NOTSELECTED;
    private Set checkedPaths;
    private JTree tree;
    private MouseHandler handler;
    /** Create a per-tree instance of the checkbox renderer. */
    public CheckBoxTreeCellRenderer(JTree tree, TreeCellRenderer original) {
    this.tree = tree;
    this.renderer = original;
    checkedPaths = new HashSet();
    checkBox = new JCheckBox();
    checkBox.setOpaque(false);
    System.out.println(checkBox.isSelected());
    checkBox.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
              trace(checkBox);
    // ActionListener actionListener = new ActionListener() {
    // public void actionPerformed(ActionEvent actionEvent) {
    // AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
    // boolean selected = abstractButton.getModel().isSelected();
    // System.out.println(selected);
    // // abstractButton.setText(newLabel);
    // checkBox.addActionListener(new ActionListener(){
    //               public void actionPerformed(ActionEvent actionEvent) {
    //                    Checkbox cb = actionEvent.getSource();
    //     boolean selected = abstractButton.getModel().isSelected();
    //     System.out.println(selected);
    checkBox.setSize(checkBox.getPreferredSize());
    private static void trace(JCheckBox cb) {
         if (cb.isSelected())
              System.out.println(cb.getText()+" is " + cb.isSelected());
         else
              System.out.println(cb.getText()+" is " + cb.isSelected());
    protected void installMouseHandler() {
    if (handler == null) {
    handler = new MouseHandler();
    addMouseHandler(handler);
    protected void addMouseHandler(MouseHandler handler) {
    tree.addMouseListener(handler);
    tree.addMouseMotionListener(handler);
    private void updateMouseLocation(Point newLoc) {
    if (mouseRow != -1) {
    repaint(mouseRow);
    mouseLocation = newLoc;
    if (mouseLocation != null) {
    mouseRow = getRow(newLoc);
    repaint(mouseRow);
    else {
    mouseRow = -1;
    if (mouseRow != -1 && mouseLocation != null) {
    Point mouseLoc = new Point(mouseLocation);
    Rectangle r = getRowBounds(mouseRow);
    if (r != null)
    mouseLoc.x -= r.x;
    mouseInCheck = isInCheckBox(mouseLoc);
    else {
    mouseInCheck = false;
    protected int getRow(Point p) {
    return tree.getRowForLocation(p.x, p.y);
    protected Rectangle getRowBounds(int row) {
    return tree.getRowBounds(row);
    protected TreePath getPathForRow(int row) {
    return tree.getPathForRow(row);
    protected int getRowForPath(TreePath path) {
    return tree.getRowForPath(path);
    public void repaint(Rectangle r) {
    tree.repaint(r);
    public void repaint() {
    tree.repaint();
    private void repaint(int row) {
    Rectangle r = getRowBounds(row);
    if (r != null)
    repaint(r);
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    installMouseHandler();
    TreePath path = getPathForRow(row);
    state = UNSELECTABLE;
    if (path != null) {
    if (isChecked(path)) {
    state = FULLSELECTED;
    else if (isPartiallyChecked(path)) {
    state = PARTIALSELECTED;
    else if (isSelectable(path)) {
    state = NOTSELECTED;
    checkBox.setSelected(state == FULLSELECTED);
    checkBox.getModel().setArmed(mouseRow == row && pressedRow == row && mouseInCheck);
    checkBox.getModel().setPressed(pressedRow == row && mouseInCheck);
    checkBox.getModel().setRollover(mouseRow == row && mouseInCheck);
    Component c = renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
    checkBox.setForeground(c.getForeground());
    if (c instanceof JLabel) {
    JLabel label = (JLabel)c;
    // Augment the icon to include the checkbox
    Icon customOpenIcon = new ImageIcon("browse.gif");
    label.setIcon(new CompoundIcon(label.getIcon()));
    return c;
    private boolean isInCheckBox(Point where) {
    Insets insets = tree.getInsets();
    int right = checkBox.getWidth();
    int left = 0;
    if (insets != null) {
    left += insets.left;
    right += insets.left;
    return where.x >= left && where.x < right;
    public boolean isExplicitlyChecked(TreePath path) {
    return checkedPaths.contains(path);
    /** Returns whether selecting the given path is allowed. The default
    * returns true. You should return false if the given path represents
    * a placeholder for a node that has not yet loaded, or anything else
    * that doesn't represent a normal, operable object in the tree.
    public boolean isSelectable(TreePath path) {
    return true;
    /** Returns whether the given path is currently checked. */
    public boolean isChecked(TreePath path) {
    if (isExplicitlyChecked(path)) {
    return true;
    else {
    if (path.getParentPath() != null) {
    return isChecked(path.getParentPath());
    else {
    return false;
    public boolean isPartiallyChecked(TreePath path) {
    Object node = path.getLastPathComponent();
    for (int i = 0; i < tree.getModel().getChildCount(node); i++) {
    Object child = tree.getModel().getChild(node, i);
    TreePath childPath = path.pathByAddingChild(child);
    if (isChecked(childPath) || isPartiallyChecked(childPath)) {
    return true;
    return false;
    private boolean isFullyChecked(TreePath parent) {
    Object node = parent.getLastPathComponent();
    for (int i = 0; i < tree.getModel().getChildCount(node); i++) {
    Object child = tree.getModel().getChild(node, i);
    TreePath childPath = parent.pathByAddingChild(child);
    if (!isExplicitlyChecked(childPath)) {
    return false;
    return true;
    public void toggleChecked(int row) {
    TreePath path = getPathForRow(row);
    boolean isChecked = isChecked(path);
    removeDescendants(path);
    if (!isChecked) {
    checkedPaths.add(path);
    setParent(path);
    repaint();
    private void setParent(TreePath path) {
    TreePath parent = path.getParentPath();
    if (parent != null) {
    if (isFullyChecked(parent)) {
    removeChildren(parent);
    checkedPaths.add(parent);
    } else {
    if (isChecked(parent)) {
    checkedPaths.remove(parent);
    addChildren(parent);
    checkedPaths.remove(path);
    setParent(parent);
    private void addChildren(TreePath parent) {
    Object node = parent.getLastPathComponent();
    for (int i = 0; i < tree.getModel().getChildCount(node); i++) {
    Object child = tree.getModel().getChild(node, i);
    TreePath path = parent.pathByAddingChild(child);
    checkedPaths.add(path);
    private void removeChildren(TreePath parent) {
    for (Iterator i = checkedPaths.iterator(); i.hasNext();) {
    TreePath p = (TreePath) i.next();
    if (p.getParentPath() != null && parent.equals(p.getParentPath())) {
    i.remove();
    private void removeDescendants(TreePath ancestor) {
    for (Iterator i = checkedPaths.iterator(); i.hasNext();) {
    TreePath path = (TreePath) i.next();
    if (ancestor.isDescendant(path)) {
    i.remove();
    /** Returns all checked rows. */
    public int[] getCheckedRows() {
    TreePath[] paths = getCheckedPaths();
    int[] rows = new int[checkedPaths.size()];
    for (int i = 0; i < checkedPaths.size(); i++) {
    rows[i] = getRowForPath(paths);
    Arrays.sort(rows);
    return rows;
    /** Returns all checked paths. */
    public TreePath[] getCheckedPaths() {
    return (TreePath[]) checkedPaths.toArray(new TreePath[checkedPaths.size()]);
    protected class MouseHandler extends MouseAdapter implements MouseMotionListener {
    public void mouseEntered(MouseEvent e) {
    updateMouseLocation(e.getPoint());
    public void mouseExited(MouseEvent e) {
    updateMouseLocation(null);
    public void mouseMoved(MouseEvent e) {
    updateMouseLocation(e.getPoint());
    public void mouseDragged(MouseEvent e) {
    updateMouseLocation(e.getPoint());
    public void mousePressed(MouseEvent e) {
    pressedRow = e.getModifiersEx() == InputEvent.BUTTON1_DOWN_MASK
    ? getRow(e.getPoint()) : -1;
    updateMouseLocation(e.getPoint());
    public void mouseReleased(MouseEvent e) {
    if (pressedRow != -1) {
    int row = getRow(e.getPoint());
    if (row == pressedRow) {
    Point p = e.getPoint();
    Rectangle r = getRowBounds(row);
    p.x -= r.x;
    if (isInCheckBox(p)) {
    toggleChecked(row);
    pressedRow = -1;
    updateMouseLocation(e.getPoint());
    public void mouseClicked(MouseEvent e){
         if(checkBox.isSelected()){
              System.out.println(checkBox.getName());
    /** Combine a JCheckBox's checkbox with another icon. */
    private final class CompoundIcon implements Icon {
    private final Icon icon;
    private final int w;
    private final int h;
    private CompoundIcon(Icon icon) {
    if (icon == null) {
    icon = new Icon() {
    public int getIconHeight() { return 0; }
    public int getIconWidth() { return 0; }
    public void paintIcon(Component c, Graphics g, int x, int y) { }
    this.icon = icon;
    this.w = icon.getIconWidth();
    this.h = icon.getIconHeight();
    public int getIconWidth() {
    return checkBox.getPreferredSize().width + w;
    public int getIconHeight() {
    return Math.max(checkBox.getPreferredSize().height, h);
    public void paintIcon(Component c, Graphics g, int x, int y) {
    if (c.getComponentOrientation().isLeftToRight()) {
    int xoffset = checkBox.getPreferredSize().width;
    int yoffset = (getIconHeight()-icon.getIconHeight())/2;
    icon.paintIcon(c, g, x + xoffset, y + yoffset);
    if (state != UNSELECTABLE) {
    paintCheckBox(g, x, y);
    else {
    int yoffset = (getIconHeight()-icon.getIconHeight())/2;
    icon.paintIcon(c, g, x, y + yoffset);
    if (state != UNSELECTABLE) {
    paintCheckBox(g, x + icon.getIconWidth(), y);
    private void paintCheckBox(Graphics g, int x, int y) {
    int yoffset;
    boolean db = checkBox.isDoubleBuffered();
    checkBox.setDoubleBuffered(false);
    try {
    yoffset = (getIconHeight()-checkBox.getPreferredSize().height)/2;
    g = g.create(x, y+yoffset, getIconWidth(), getIconHeight());
    checkBox.paint(g);
    if (state == PARTIALSELECTED) {
    final int WIDTH = 2;
    g.setColor(UIManager.getColor("CheckBox.foreground"));
    Graphics2D g2d = (Graphics2D)g;
    g2d.setStroke(new BasicStroke(WIDTH, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    int w = checkBox.getWidth();
    int h = checkBox.getHeight();
    g.drawLine(w/4+2, h/2-WIDTH/2+1, w/4+w/2-3, h/2-WIDTH/2+1);
    g.dispose();
    finally {
    checkBox.setDoubleBuffered(db);
    private static String createText(TreePath[] paths) {
    if (paths.length == 0) {
    return "Nothing checked";
    String checked = "Checked:\n";
    for (int i=0;i < paths.length;i++) {
    checked += paths[i] + "\n";
    return checked;
    public static void main(String[] args) {
    try {
    final String SWITCH = "toggle-componentOrientation";
    try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (ClassNotFoundException e1) {
                   e1.printStackTrace();
              } catch (InstantiationException e1) {
                   e1.printStackTrace();
              } catch (IllegalAccessException e1) {
                   e1.printStackTrace();
              } catch (UnsupportedLookAndFeelException e1) {
                   e1.printStackTrace();
    JFrame frame = new JFrame("Tree with Check Boxes");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final DefaultMutableTreeNode a = new DefaultMutableTreeNode("Node 1");
    for(int i =0 ; i<3; i++ ){
         DefaultMutableTreeNode b = new DefaultMutableTreeNode("ChildNode "+i);
         a.add(b);
    DefaultMutableTreeNode e = new DefaultMutableTreeNode("Node 2");
    for(int i =0 ; i<3; i++ ){
         DefaultMutableTreeNode f = new DefaultMutableTreeNode("ChildNode "+i);
         e.add(f);
    DefaultMutableTreeNode al = new DefaultMutableTreeNode("Sample");
    al.add(a);
    al.add(e);
    final JTree tree = new JTree(al);
    final CheckBoxTreeCellRenderer r =
    new CheckBoxTreeCellRenderer(tree, tree.getCellRenderer());
    tree.setCellRenderer(r);
    int rc = tree.getRowCount();
    tree.getActionMap().put(SWITCH, new AbstractAction(SWITCH) {
    public void actionPerformed(ActionEvent e) {
    ComponentOrientation o = tree.getComponentOrientation();
    if (o.isLeftToRight()) {
    o = ComponentOrientation.RIGHT_TO_LEFT;
    else {
    o = ComponentOrientation.LEFT_TO_RIGHT;
    tree.setComponentOrientation(o);
    tree.repaint();
    int mask = InputEvent.SHIFT_MASK|Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
    tree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_O, mask), SWITCH);
    final JTextArea text = new JTextArea(createText(r.getCheckedPaths()));
    text.setPreferredSize(new Dimension(200, 100));
    tree.addMouseListener(new MouseAdapter() {
    public void mouseReleased(MouseEvent e) {
    // Invoke later to ensure all mouse handling is completed
    SwingUtilities.invokeLater(new Runnable() { public void run() {
    text.setText(createText(r.getCheckedPaths()));
    JScrollPane pane = new JScrollPane(tree);
    frame.getContentPane().add(pane);
    // frame.getContentPane().add(new JScrollPane(text), BorderLayout.SOUTH);
    frame.pack();
    frame.setSize(600,400);
    frame.setVisible(true);
    catch(Exception e) {
    e.printStackTrace();
    System.exit(1);
    now i need to get nodes names which has been selected, how can i do this
    can anyone help me ...
    regards,
    shobi

    Also, use code tags and post a SSCCE -- I'm sure more of your posted code is irrelevant to your question and few people are going to look at a code listing that long.
    [http://mindprod.com/jgloss/sscce.html]

  • Help in add checkbox in jtree

    hi all.... i wan new in swing
    how can i add check box in each node of my jtree?
    tis r my full program..... pls help me... tz..........very much
    //FileTreePanel.java
    package com.y
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import com.y.FileSystemModel;
    public class FileTreePanel extends JPanel {
    private JTree fileTree;
    private FileSystemModel fileSystemModel;
    private JTextArea fileDetailsTextArea;
    public FileTreePanel( String directory )
    fileDetailsTextArea = new JTextArea();
    fileDetailsTextArea.setEditable( false );
    fileSystemModel = new FileSystemModel(
    new File( directory ) );
    fileTree = new JTree( fileSystemModel );
    fileTree.setEditable( true );
    fileTree.addTreeSelectionListener(
    new TreeSelectionListener() {
    public void valueChanged(
    TreeSelectionEvent event )
    File file = ( File )
    fileTree.getLastSelectedPathComponent();
    fileDetailsTextArea.setText(
    getFileDetails( file ) );
    JSplitPane splitPane = new JSplitPane(
    JSplitPane.HORIZONTAL_SPLIT, true,
    new JScrollPane( fileTree ),
    new JScrollPane( fileDetailsTextArea ) );
    setLayout( new BorderLayout() );
    add( splitPane );
    } // end FileTreePanel constructor
    public Dimension getPreferredSize()
    return new Dimension( 400, 200 );
    private String getFileDetails( File file )
    // do not return details for null Files
    if ( file == null )
    return "";
    StringBuffer buffer = new StringBuffer();
    buffer.append( "Name: " + file.getName() + "\n" );
    buffer.append( "Path: " + file.getPath() + "\n" );
    buffer.append( "Size: " + file.length() + "\n" );
    return buffer.toString();
    public static void main( String args[] )
    if ( args.length != 1 )
    System.err.println(
    "Usage: java FileTreeFrame <path>" );
    else {
    JFrame frame = new JFrame( "JTree FileSystem Viewer" );
    FileTreePanel treePanel = new FileTreePanel( args[ 0 ] );
    frame.getContentPane().add( treePanel );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.pack();
    frame.setVisible( true );
    } // end method main
    // FileSystemModel.java
    package com.y;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class FileSystemModel implements TreeModel {
    private File root;
    private Vector listeners = new Vector();
    public FileSystemModel( File rootDirectory )
    root = rootDirectory;
    // get hierarchy root (root directory)
    public Object getRoot()
    return root;
    public Object getChild( Object parent, int index )
    File directory = ( File ) parent;
    String[] children = directory.list();
    return new TreeFile( directory, children[ index ] );
    public int getChildCount( Object parent )
    // get parent File object
    File file = ( File ) parent;
    // get number of files in directory
    if ( file.isDirectory() ) {
    String[] fileList = file.list();
    if ( fileList != null )
    return file.list().length;
    return 0; // childCount is 0 for files
    // return true if node is a file, false if it is a directory
    public boolean isLeaf( Object node )
    File file = ( File ) node;
    return file.isFile();
    // get numeric index of given child node
    public int getIndexOfChild( Object parent, Object child )
    // get parent File object
    File directory = ( File ) parent;
    // get child File object
    File file = ( File ) child;
    // get File list in directory
    String[] children = directory.list();
    // search File list for given child
    for ( int i = 0; i < children.length; i++ ) {
    if ( file.getName().equals( children[ i ] ) ) {
    // return matching File's index
    return i;
    return -1; // indicate child index not found
    } // end method getIndexOfChild
    // invoked by delegate if value of Object at given
    // TreePath changes
    public void valueForPathChanged( TreePath path,
    Object value )
    // get File object that was changed
    File oldFile = ( File ) path.getLastPathComponent();
    // get parent directory of changed File
    String fileParentPath = oldFile.getParent();
    // get value of newFileName entered by user
    String newFileName = ( String ) value;
    // create File object with newFileName for
    // renaming oldFile
    File targetFile = new File(
    fileParentPath, newFileName );
    // rename oldFile to targetFile
    oldFile.renameTo( targetFile );
    // get File object for parent directory
    File parent = new File( fileParentPath );
    // create int array for renamed File's index
    int[] changedChildrenIndices =
    { getIndexOfChild( parent, targetFile) };
    // create Object array containing only renamed File
    Object[] changedChildren = { targetFile };
    // notify TreeModelListeners of node change
    fireTreeNodesChanged( path.getParentPath(),
    changedChildrenIndices, changedChildren );
    } // end method valueForPathChanged
    // notify TreeModelListeners that children of parent at
    // given TreePath with given indices were changed
    private void fireTreeNodesChanged( TreePath parentPath,
    int[] indices, Object[] children )
    // create TreeModelEvent to indicate node change
    TreeModelEvent event = new TreeModelEvent( this,
    parentPath, indices, children );
    Iterator iterator = listeners.iterator();
    TreeModelListener listener = null;
    // send TreeModelEvent to each listener
    while ( iterator.hasNext() ) {
    listener = ( TreeModelListener ) iterator.next();
    listener.treeNodesChanged( event );
    } // end method fireTreeNodesChanged
    // add given TreeModelListener
    public void addTreeModelListener(
    TreeModelListener listener )
    listeners.add( listener );
    // remove given TreeModelListener
    public void removeTreeModelListener(
    TreeModelListener listener )
    listeners.remove( listener );
    // TreeFile is a File subclass that overrides method
    // toString to return only the File name.
    private class TreeFile extends File {
    // TreeFile constructor
    public TreeFile( File parent, String child )
    super( parent, child );
    public String toString()
    return getName();
    }

    Crossposted in Swing forum.

  • JTREE with CheckBox Option

    Hi All,
    Can somebody help in how to add a CheckBox in JTREE node concept.
    Please let me if sites are there for the same.
    Rgds
    Sudhama

    * The CheckedTree is an extension to JTree with the additional functioanlity that
    * the nodes can be checked or unchecked using a checkbox.
    * <p>
    * Each node in the tree contains a checkbox.
    * @author anoopkc
    public class CheckedTree extends JTree {
        private CustomRenderer renderer = null;
        private List<TreePath> selectedNodes = null;
         * Initialises the checked tree
        public CheckedTree() {
            this.selectedNodes = new ArrayList<TreePath>();
            this.setTreeProperties();
         * Sets the properties of the tree
        private void setTreeProperties() {
            this.renderer = new CustomRenderer(this);
            super.setCellRenderer(renderer);
            super.getSelectionModel().setSelectionMode(4);
            super.addMouseListener(new MouseAdapter() {
                 * Handles the click on the tree nodes.
                 * When mouse is clicked on a node, the node is added in the
                 * list of selected rows in the tree.
                 * @param e
                public void mousePressed(MouseEvent e) {
                    TreePath path = getPathForLocation(e.getX(), e.getY());
                    if (path != null) {
                        addSelectedNode(path);
                        updateUI();
         * This method adds the selected path in to the list of selected nodes.
         * If the path is already exists, it is removed from the list.
         * @param path
        private void addSelectedNode(TreePath path) {
            if (selectedNodes.indexOf(path) == -1) {
                selectedNodes.add(path);
            } else {
                selectedNodes.remove(path);
         * This method checks whether a given tree path is selected or not
         * @param path
         * @return true if selected
        public boolean isSelected(TreePath path) {
            if (this.selectedNodes.indexOf(path) == -1) {
                return false;
            return true;
         * Returns the list of selected columns
         * @return list of selected columns
        public List<TreePath> getSeelctedNodes() {
            return selectedNodes;
    * This class creates the renderer for the checked tree
    * @author anoopkc
    class CustomRenderer extends JPanel implements TreeCellRenderer {
        private JLabel label = null;
        private JCheckBox checkBox = null;
        private CheckedTree tree = null;
         * Initialises the renderer
         * @param checkedTree
        public CustomRenderer(CheckedTree checkedTree) {
            this.tree = checkedTree;
            this.prepareComponent();
         * Prepares the component
        private void prepareComponent() {
            creatComponent();
            this.packComponents();
         * Creates the component
        private void creatComponent() {
            this.label = new JLabel();
            this.label.setPreferredSize(new Dimension(100, 21));
            this.label.setForeground(UIManager.getColor("Tree.textForeground"));
            this.label.setOpaque(true);
            this.checkBox = new JCheckBox();
            this.checkBox.setBackground(UIManager.getColor("Tree.textBackground"));
         * Packs the components
        private void packComponents() {
            setLayout(new GridBagLayout());
            setBackground(Color.WHITE);
            GridBagConstraints gbcCheckBox = new GridBagConstraints();
            gbcCheckBox.gridx = 0;
            GridBagConstraints gbcLabel = new GridBagConstraints();
            gbcLabel.gridx = 0;
            gbcLabel.gridx = 1;
            gbcLabel.weightx = 1;
            gbcLabel.fill = GridBagConstraints.HORIZONTAL;
            add(this.checkBox, gbcCheckBox);
            add(this.label, gbcLabel);
         * Returns the tree cell renderer component
         * @param tree
         * @param value
         * @param selected
         * @param expanded
         * @param leaf
         * @param row
         * @param hasFocus
         * @return component
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            TreePath path = tree.getPathForRow(row);
            label.setText(value.toString());
            label.setIcon(new ImageIcon("icons/smiley.gif"));
            if (selected) {
                label.setBackground(new Color(220, 220, 200));
            } else {
                label.setBackground(Color.WHITE);
            if (this.tree.isSelected(path)) {
                this.checkBox.setSelected(true);
            } else {
                checkBox.setSelected(false);
            return this;
    }

  • JTree selection problem when using custom renderer and editor

    Hello:
    I created a JTree with custom renderer and editor.
    The customization makes JCheckBox to be the component
    responsible for editing and rendering.
    The problem is that when I click on the node with the checkbox
    the JTree selection model does not get updated.
    Without customizations of the editor and renderer the MouseEvent would be fired and BasicTreeUI$MouseHandler.mousePressed() method would call
    the selectPathForEvent() method which would be responsible for updating
    the selection model. At the same time if I attach a mouse listener to the JTree (customized) I see the events when clicking on the nodes. It seems like the MouseEvent gets lost and somehow as a result of which the selection model does not get updated.
    Am I missing something?
    Thanks
    Alexander

    You probably forgot to call super.getTreeCellRendererComponent(...) at the beginning of your getTreeCellRendererComponent(...) method in your custom renderer.
    Or maybe in the getTreeCellEditorComponent(...) of the TreeCellEditor...

  • Attaching a checkbox to tree

    is it possible in java to attach a checkbox to jtree ?
    if so how to do it ?

    http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxNodeTreeSample.htm

  • Checkbox that only change status if user clicks in box

    Hi,
    I am using CheckBox in JTree and I have problem: If users click on that check box (on the text), it immediately change its status. How can I make it to change its status, only when user clicks on the box and not on the text? It should still take focus when user clicks on the text, but not change its status.
    Source of current implementation: http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxNodeTreeSample.htm
    Thank you,
    Sasa

    Well, I suppose you could fiddle with the event handling in JCheckBox, but an easier way would be creating a component which is basically a composite of the JCheckBox (without text) and a JLabel. Make your editor return a JPanel with a BorderLayout and install the checkbox in the west panel and the label in center.

  • JFrame layout help

    Hi!
    I cant find any layout that fits me...
    I want to set a layout on a JFrame so that every component I place on the frame will be placed in a vertical line. The components also have to be as far up as possible (not like GridLayout) and to the left.
    Thanks!

    Hi, now I get the layout. But it gets very small. Why is this?
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.BoxLayout;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    public class TestCheckboxTree extends JFrame
         public TestCheckboxTree()
              super("Testing Checkboxes on JTree!");
              JScrollPane scrollpane = new JScrollPane();
              scrollpane.setPreferredSize(new Dimension(300, 300));
              scrollpane.setAlignmentX(LEFT_ALIGNMENT);
              JPanel panel = new JPanel();
              panel.setBackground(Color.WHITE);
              panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
              JTree tree = CheckboxTree.makeCheckTree(new FolderTree("/home/"));
              JTree tree2 = CheckboxTree.makeCheckTree(new FolderTree("/home/rejeep/programming"));
              panel.add(tree);
              panel.add(tree2);
              scrollpane.getViewport().add(panel);
              add(scrollpane);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setSize(500, 500);
              setVisible(true);
         public static void main(String args[])
              new TestCheckboxTree();
    }

  • Problem with Jtree and a checkbox

    Hello,
    I have a problem with my tree implementation.
    I create a tree and i want to add a checkbox in each node.
    this is my code :
    DefaultMutableTreeNode root;
    root = new DefaultMutableTreeNode(new JCheckBox());
    DefaultTreeModel model = new DefaultTreeModel(root);
    _tree = new JTree(model);
    eastpane.add(tree);
    THe problem is that my checkbox doesn't appear. And a message appears
    instead of my checkbox.
    But my tree appears.
    Can anyone help me .
    Thanks

    You can provide a cell renderer to the JTree to paint the checkBox.
    The following code checks or unchecks the box with each click also:
    _tree.setCellRenderer(new DefaultTreeCellRenderer()
      private JCheckBox checkBox = null;
      public Component getTreeCellRendererComponent(JTree tree,
                                                    Object value,
                                                    boolean selected,
                                                    boolean expanded,
                                                    boolean leaf,
                                                    int row,
                                                    boolean hasFocus)
        // Each node will be drawn as a check box
        if (checkBox == null)
          checkBox  = new JCheckBox();
          checkBox .setBackground(tree.getBackground());
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
        checkBox.setText(node.getUserObject().toString());
        checkBox.setSelected(selected);
        return checkBox;
    });

  • Displaying a jtree with checkboxes and enabling some default checkboxes

    I have created a jtree displaying a list of nodes hierarchically ,and created a checkbox for each node as well.
    My problem is having created the jtree with checkboxes i need to have some of the nodes in the hierarchy checked by default on first launch of the gui.To do this i read a list of treepaths from a file and would want to traverse the tree and enable the node after finding it,which is what i am having issue with.
    Your solution would be appreciated as i am a newbie and having got this far, feel like i need some back up :)
    Thanks & Regards
    Shashi

    I have created a jtree displaying a list of nodes hierarchically ,and created a checkbox for each node as well.
    My problem is having created the jtree with checkboxes i need to have some of the nodes in the hierarchy checked by default on first launch of the gui.To do this i read a list of treepaths from a file and would want to traverse the tree and enable the node after finding it,which is what i am having issue with.
    Your solution would be appreciated as i am a newbie and having got this far, feel like i need some back up :)
    Thanks & Regards
    Shashi

  • Selcting Multiple  CheckBoxe in a JTREE without holding CTRL / SHIFT

    HI,
    My JTree is having JCheckBOxes as nodes .... Now the problem is i want to select multiple nodes (checkboxes) with out holding CTRL/SHIFT key .
    Please help regarding this issue ..
    The code of my renderer class is as below:
    * MyTreeRendered.java
    * Created on April 27, 2006, 7:42 PM
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    public class MyTreeRendered extends DefaultTreeCellRenderer  {
        private JCheckBox cb ;
        /** Creates a new instance of MyTreeRendered */
        public MyTreeRendered() {
        public Component getTreeCellRendererComponent(
                            JTree tree,
                            Object value,
                            boolean sel,
                            boolean expanded,
                            boolean leaf,
                            int row,
                            boolean hasFocus){
           if(cb == null) {
               cb = new JCheckBox();
               cb.setBackground(tree.getBackground());
           DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
           cb.setText(node.getUserObject().toString());
           cb.setSelected(sel);
           return cb;
    }

    These are the methods which seem to define that behaviour:
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/basic/BasicTreeUI.html#isToggleSelectionEvent(java.awt.event.MouseEvent)
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/basic/BasicTreeUI.html#isMultiSelectEvent(java.awt.event.MouseEvent)
    You'd have to write your own TreeUI and override them.

  • Selection Of checkbox in the JTree

    Hi all,
    I have a very small problem in JTree.
    The JTree is with checkbox.When ever I select on the node the simultaneous chechbox is selected.
    But some time with the same operation the checkbox is not selected.
    Here,I attache the part of code which is responsible for my problem.
    public void mouseClickedNodeSelectionListener(MouseEvent e)
            int x = e.getX();
            int y = e.getY();
            int row = tree.getRowForLocation(x, y);
            TreePath path = tree.getPathForRow(row);
            //TreePath path = tree.getSelectionPath();
            if (path != null) {
                if(/*e.getClickCount()==1 &&*/ ElmsConstants.isDoubleClicked)
                    if(lastPath!=null)
                        tree.setSelectionPath(lastPath);
                    return;
                lastPath = path;
                CheckNode node = (CheckNode) path.getLastPathComponent();
                int selectedId = 0;
                if(node.getElmsData()!=null)
                    selectedId = (node.getElmsData().getId()).intValue();
                if(lastSelectedId==selectedId)
                    boolean isSelected = !(node.isSelected());
                    node.setSelected(isSelected);
                    tree.updateUI();
                    ((DefaultTreeModel) tree.getModel()).nodeChanged(node);
                    if (row == 0) {
                        try{
                            tree.revalidate();
                            tree.repaint();
                        }catch(Exception eE)
                            System.out.println("Exception in Tree repaint");
                lastSelectedId=selectedId;
    }Any Body Please help me.
    Thank you,
    Ananda

    It's hard to say what's the problem when you post this little code.
    But probably the problem is that you're listening for mouse click event.
    This event only fires when you click the mouse without moving it.
    If by mistake you move the mouse while you click it you will not get a mouse click event.
    You can use the mousePressed or mouseReleased events instead.
    Anyway I would implement this with a custom editor instead of listening to mouse events.
    See example here: [http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxNodeTreeSample.htm]

  • How can create a JTree with cellRender is checkbox realized multiple selec

    How can create a JTree with cellRender is checkbox realized multiple selection function.thanks for every
    one's help.

    Hi,
    1. Create a value node in your context name Table and set its cardinality to 0:n
    2. Create 2 value attributes within the Table node name value1 and value2
    3. Goto Outline view> Right click on TransparentUIContainer>Apply Template> Select Table>mark the node Table and it's attributes.
    you have created a table and binded its value to context
    Table UI properties
    4.Set Selection Mode to Multi
    5.Set Visible Row Count to 5
    6.ScrollableColCount to 5
    In your implemetaion, you can add values to table as follow:
    IPrivate<viewname>.ITableElement ele = wdContext.nodeTable().createTableElement();
    ele.setValue1(<value>);
    ele.setValue2(<value>);
    wdContext.nodeTable().addElement(ele);
    The above code will allow you to add elements to your table node.
    Regards,
    Murtuza

  • Using JTree with checkbox

    Hi All,
    I have a link for implementation of JTree with Checkbox
    http://www.jroller.com/santhosh/date/20050610 He has implemented exactly what i want but i am unable to understand the use of all the classes. Really difficult to understand
    So what i did was create a few objects with Checkbox class from AWT package and then added then to JTree using the DefaultMutableTreeStruture i got the tree working but not able to get the Checkboxex
    Can any one explain me how i can implement this senario
    I am trying different search creterias but unable to find a right detailed explanation to my query
    Rgds
    Aditya

    where did you find DefaultMutableTreeStructure?

  • JTree, where every node has a checkbox.

    I need a JTree, where every node has a checkbox. Each checkbox will be selected if all childnodes are selected, deselected if all childnodes are deselected, and semi-selected if some childnodes are selected and some are not.
    I've seen this in some applications. It would really surprise me if no-one has done this yet, but I've googled without results.
    If you have some links or samples that can help me and send them I'll appreciate it very much.
    Thank you

    Hello,
    I guess you want those JCheckBoxes to act as editors (not just renderers of their model node's state).
    What is supposed to happen when I click on a half selected parent node? Will it select all sub nodes? How do you want to represent half selection?

Maybe you are looking for