JTree selection questions

I am wanting a user to select multiple top level folders in the tree.
Do I simply have the user ctrl select multiple folders? Or is it possible to place a checkboxes next to the tree items?
If I have a button that trigger a function. How does that function know what items were selected in the tree?

http://java.sun.com/docs/books/tutorial/uiswing/events/treeexpansionlistener.html
OR
let the JPanel that contains the tree implement MouseListener
then
     public void mouseClicked(MouseEvent e) {
          // right-click?
          if (e.getButton() == MouseEvent.BUTTON3)
               return;
          int x = e.getX();
          int y = e.getY();
          TreePath selPath = tree.getClosestPathForLocation(x, y);
          if (selPath == null)
               return null;
          DefaultMutableTreeNode nodeClicked = (DefaultMutableTreeNode) selPath.getLastPathComponent();
          Rectangle rect = tree.getPathBounds(selPath);
if(rect.contains(x,y))
//you get the idea...
}

Similar Messages

  • 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...

  • JTree sizing question...

    Hello:
    I have a JTree for which each cell contains a button. I have written a renderer that renders the button, and I realize that I have to do some special stuff to capture a click on the button. My question is unrelated to all of that.
    The problem is that over time, the labels on my buttons change (and may become longer (wider)), but the tree size does not change. In fact, when I update the button label and the tree is re-rendered the rendering of the button gets "chopped off". I've put the tree in a scroll pane, but this doesn't help - the right side of some of the buttons get cut off to the original tree size. I've tried lots of different variations on setPreferredSize, calling repaint, etc, and am not having any luck. I've put together a demonstration of this behavior in a smallish application that I'm posting here, where I create a 2 node tree with buttons that read "Hi", then I change the button labels to "Goodbye" and re-render. You'll see that the button's are cut off about halfway through the button.
    In case its important - I'm running java version 1.5.0_07 on a 32-bit Linux box.
    Any help would be greatly appreciated. Thanks in advance!
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    public class JTreeQuestion
      public static void main(String [] args)
        JTreeFrame f = new JTreeFrame();
        f.pack();
        f.setLocation(30, 30);
        //Draws buttons with "Hi" (short string)
        f.setVisible(true);
        ButtonNode.updateString("Goodbye");
        //Draws buttons with longer string, buttons get "cut off"
        f.repaint();
    class JTreeFrame extends JFrame
      JTree tree;
      JScrollPane treeView;
      public JTreeFrame()
        super("My Tree");
        DefaultMutableTreeNode root;
        root = new DefaultMutableTreeNode(new ButtonNode());
        root.add(new DefaultMutableTreeNode(new ButtonNode()));
        tree = new JTree(root);
        tree.setCellRenderer(new ButtonNodeRenderer());
        treeView = new JScrollPane(tree);
        add(treeView);
    class ButtonNode
      public static String str = "Hi";
      public static void updateString(String inStr)
      { str = inStr; }
      String getStr()
      { return str; }
    class ButtonNodeRenderer extends DefaultTreeCellRenderer
      public Component getTreeCellRendererComponent(JTree tree,
                              Object value, boolean sel, boolean expanded,
                              boolean leaf, int row, boolean hasFocus)
        Box theBox = new Box(BoxLayout.X_AXIS);
        super.getTreeCellRendererComponent(tree, value, sel, expanded,
                                           leaf, row, hasFocus);
        DefaultMutableTreeNode jtreeNode = (DefaultMutableTreeNode)value;
        theBox.add(new JButton(((ButtonNode)jtreeNode.getUserObject()).getStr()));
        return (theBox);
    }

    For those who are interested. The DefaultTreeModel has a method named nodeChanged() that tells the tree model that a specific node has changed, and the model re-interprets the cell causing its sizse to change as necessary, so that the full button is rendered now.
    Basically what I did was instead of calling repain, I call a method that I wrote that loops through all the tree nodes, indicates they have changed, then repaint's, and it all works out. My trees are relatively small, so this is fine, but if others face the same problem, you'll probably want to selectively indicate which nodes have changed so the tree model doesn't have to do more work than necessary.

  • Problem with jtree selection

    Hi all,
    I've got a JTree that represents a sort of data that I'm going to change dynamically in my application. I'd like to reset the selection of the user to the leaf she has selected before the change to the tree structure.
    First of all my tree uses DefaultMutableTreeNode to build each node, and each DefaultMutableTreeNode contains a SingleKeyValue object, that is a key-value object (two strings) and that has an hashcode defined as follows:
    public class SingleKeyValue extends BaseKeyValue{
          * The key of the database object.
         protected String key = null;
          * The description of this object.
         protected String value = null;
         public int hashCode() {
              return this.key.hashCode();
         I hope the hashcode can help me finding the right object even when its value changes (but the key is the same). The construction of the tree is the following:
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("The root");
    // iterate and build each node
    SingleKeyValue object = new SingleKeyValue("key","value");
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(object);
    root.add(node);
    DefaultTreeModel model = new DefaultTreeModel(root);
    JTree  tree = new JTree(model);             
                so the tree is associated to a DefaultTreeModel. Then, when I need to change something in the tree I rebuild the tree and all leafs (with the SingleKeyValues) and rebuild the model:
              TreeModel treeModel = this.myTree.getModel();
              TreeSelectionModel selectionModel = this.myTree.getSelectionModel();
              DefaultTreeModel defaultTreeModel = null;
              DefaultTreeSelectionModel defaultTreeSelectionModel = null;
              TreePath selectedPath = null;
              TreeNode root = null;
              Logger.info("SimpleTreePanel.refreshDatabaseView: treemodel "+treeModel + " selectionModel " + selectionModel);
              if( treeModel != null && treeModel instanceof DefaultTreeModel ) {
                   defaultTreeModel = (DefaultTreeModel) treeModel;
                   root = this.getRoot();
                   // get the selection
                   if( selectionModel != null && selectionModel instanceof DefaultTreeSelectionModel ){
                        defaultTreeSelectionModel = (DefaultTreeSelectionModel) selectionModel;
                        selectedPath = defaultTreeSelectionModel.getSelectionPath();
                        Logger.warn("Selection path of the tree: "+selectedPath);
                   // rebuild the tree
                   defaultTreeModel.setRoot(root);
                   // set the selected element
                   defaultTreeSelectionModel.setSelectionPath(selectedPath);The problem is that after the above code the tree is all closed, no leaf are selected. I guess the problem is with the SingleKeyValueObject because I've tried the default model and it works with, for example, simple strings. Any idea about?
    Thanks,
    Luca

    Here's a complete test program that creates a few SingleKeyValue objetcs (objects with a key and a description) and that then places them into a JTree using the DefaultMutableTreeNode. After that, the selection of user is took and one node is changed, but while the selection is working, the reload/refresh of the tree is not.
    Any idea about how to work on it?
    public class SingleKeyValue extends BaseKeyValue{
          * The key of the database object.
         protected String key = null;
          * The description of this object.
         protected String value = null;
         // constants related to the type of the table this object refers to
         public static final String COMPETENCE = "competenza";
         public static final String FAMILY            = "famiglia_competenza";
         public static final String ROLE              = "ruolo";
         public static final String PROVINCE      = "provincia";
         public static final String KNOWLEDGE  = "titolo_studio";
         public final static String OBJECTIVE      = "obiettivo";
         public final static String PERSON         = "persona";
         public SingleKeyValue( String key, String value, String table){
              super();
              this.key = key;
              this.value = value;
              this.SQLTable = table;
          * @return the key
         public final String getKey() {
              return key;
          * @param key the key to set
         public final void setKey(String key) {
              this.key = key;
          * @return the value
         public final String getValue() {
              return value;
          * @param value the value to set
         public final void setValue(String value) {
              this.value = value;
          * Shows this element.
         public String toString(){
              String ret;
              if( this.showKey ){
                   ret =  this.label + this.key +" { "+ this.value +" }";
              else
                   ret = this.label + this.value;
              // trim the string
              if( ret.length() > this.maxLength )
                   return ret.substring(0 , this.maxLength);
              else
                   return ret;
          * The hash code of this object is the hash code of the key.
          * @return the hash code of the key of the object
         public int hashCode() {
              return this.key.hashCode();
          * Returns true if the object passed is a single key value equals (i.e., with the same key) of this one.
         public boolean equals(Object o){
              if( o== null || (! (o instanceof SingleKeyValue) ) )     return false;
              else
                   return (this.hashCode() == o.hashCode());
         public static void main(String argv[]) throws Exception{
             SingleKeyValue skv1 = new SingleKeyValue("Key1","Description1", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv2 = new SingleKeyValue("Key1a","Description1a", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv3 = new SingleKeyValue("Key1b","Description1b", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv4 = new SingleKeyValue("Key2","Description2", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv5 = new SingleKeyValue("Key2a","Description2a", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv6 = new SingleKeyValue("Key2b","Description2b", SingleKeyValue.COMPETENCE);
             DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("root");
             DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(skv1);
             DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(skv2);
             DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(skv3);
             DefaultMutableTreeNode node4 = new DefaultMutableTreeNode(skv4);
             DefaultMutableTreeNode node5 = new DefaultMutableTreeNode(skv5);
             DefaultMutableTreeNode node6 = new DefaultMutableTreeNode(skv6);
             rootNode.add(node1);
             node1.add(node2);
             node1.add(node3);
             rootNode.add(node4);
             node4.add(node5);
             node4.add(node6);
             JTree tree = new JTree(rootNode);
             JFrame f = new JFrame("Tree try");
             f.add( new JScrollPane(tree) );
             f.setSize(300,300);
             f.setVisible(true);
             System.out.println("Please select a node within 10 seconds");
             Thread.sleep(10000);
             // now get the user selection
         TreeModel treeModel = tree.getModel();
         TreeSelectionModel selectionModel = tree.getSelectionModel();
         DefaultTreeModel defaultTreeModel = null;
         DefaultTreeSelectionModel defaultTreeSelectionModel = null;
         TreePath selectedPath = null;
         TreeNode root = null;
         if( treeModel != null && treeModel instanceof DefaultTreeModel ) {
              defaultTreeModel = (DefaultTreeModel) treeModel;
              // get the selection
              if( selectionModel != null && selectionModel instanceof DefaultTreeSelectionModel ){
                   defaultTreeSelectionModel = (DefaultTreeSelectionModel) selectionModel;
                   selectedPath = defaultTreeSelectionModel.getSelectionPath();
              // rebuild the tree
              node1.setUserObject(new SingleKeyValue("key20","key changed",SingleKeyValue.FAMILY));
              defaultTreeModel.reload();
              // set the selected element
              defaultTreeSelectionModel.setSelectionPath(selectedPath);
    }

  • Parameter selection question

    I want to make a report that gives the user the option to do one of following:
    (1) Select Top 5 Used Profile IDs
    (2) Select Top 5 Random Profile IDs
    (3) Choose Up to 5 Desired Profile IDs
    How can I make a parameter that once selected will either, with option 1 or 2 pass the selected IDs from a SQL Command, or with option 3 to select the profile IDs themselves?  Is this possible?
    I am using CR 11.5 and this will be implemented with the Viewer through a front-end application.

    hi Wesley,
    you'd really need to post this question to a forum particular to your database. Commands are written in your db syntax.
    mostly you'd need to know if your database actually supports a row level random function for the option number (2). some db's don't...i.e. they support a query level random function where the random number is a single number per query versus a different number for each row. if that's the case you'll need to look for a workaround particular to your db.
    for the other options look into seeing whether or not your database supports a CASE statement for the ORDER BY clause and the WHERE clause as you'd need to either use the WHERE clause for picking 5 user entered profile ID's or the ORDER BY clause to get the Top 5 Used Profile ID's.
    so given your db and version this type of command is possible.
    -jamie

  • JTree Selection Behavior with Custom TreeCellEditor

    I've recently had the need to build a custom TreeCellEditor with a JTree that allows single path selection. I've toyed around with it but don't understand it. When a node is clicked, the editor takes over rendering/handling the cell, and a TreeSelectionEvent is fired from the tree, but the isSelected boolean value passed to the TreeCellEditor is initially false. Then on a second click of the same path in the tree, no TreeSelectionEvent is fired, but the isSelected boolean value is true. It's as if the tree selection is occuring after the editor renders the cell. I would like the cell to appear selected on the first click. Can anyone shed some light on why this is happening and how I can fix it?
    I included some code to demonstrate the problem below (though no actual editing takes place; the test code is only to demonstrate how the cells only appear selected with a yellow background after the second click of the same cell; note also that the valueChanged only executes on the first click). This test was run on Windows with Java 1.5.
    public class TestTreeCellEditor extends JLabel implements TreeCellEditor {
         private String st;
         public TestTreeCellEditor() {
              setOpaque(true);
         public Component getTreeCellEditorComponent(JTree tree, Object value,
                   boolean isSelected, boolean expanded, boolean leaf, int row) {
              this.st = value.toString();
              setBackground(isSelected? Color.YELLOW : Color.WHITE);
              setText(st);
              return this;
         public void addCellEditorListener(CellEditorListener l) {
              // not important for test
         public void cancelCellEditing() {
              this.st = null;
         public Object getCellEditorValue() {
              return st;
         public boolean isCellEditable(EventObject anEvent) {
              return true;
         public void removeCellEditorListener(CellEditorListener l) {
              // not important for test
         public boolean shouldSelectCell(EventObject anEvent) {
              return true;
         public boolean stopCellEditing() {
              return true;
    public class TestTreeCellEditorFrame extends JFrame implements TreeSelectionListener {
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        launchGUI();
         private static void launchGUI() {
              TestTreeCellEditorFrame frame = new TestTreeCellEditorFrame();
              JPanel treePanel = new JPanel();
              DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root node");
              DefaultMutableTreeNode childNode = new DefaultMutableTreeNode("Child 1");
              rootNode.add(childNode);
              childNode = new DefaultMutableTreeNode("Child 2");
              rootNode.add(childNode);
              JTree testTree = new JTree(rootNode);
              testTree.addTreeSelectionListener(frame);
              testTree.setCellEditor(new TestTreeCellEditor());
              testTree.setEditable(true);
              testTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
              treePanel.add(testTree);
              frame.setContentPane(treePanel);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(600,400);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public void valueChanged(TreeSelectionEvent event) {
              TreePath path = event.getNewLeadSelectionPath();
              if (path != null) {
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                   System.out.println("TreeSelectionEvent on " + node.getUserObject().toString());
    }

    Since my last post, I decided that I do want to be able to edit a cell that is not selected. In particular, when using a tree with checkboxes. What I'm doing for the time being, which works well enough, is to highlight the cell based on the isSelected value in combination with calling tree.stopEditing() in a TreeSelectionListener valueChanged method. This is somewhat of a hack solution, and has the side effect of a cell not appearing selected until the mouseReleased event. I'm still looking for a better solution, but for now it works well enough.

  • Jtree Select node and change leafs icon problem

    Hi All,
    i create a tree and implement a TreeSelectionListener:
    my mission is whenever i select a node i need to change the icon of this node (for now.later i will have to find if it have childrens).
    import java.awt.Color;
    import java.awt.Component;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    import java.util.Vector;
    import javax.swing.ImageIcon;
    import javax.swing.JTree;
    import javax.swing.event.TreeExpansionEvent;
    import javax.swing.event.TreeExpansionListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreeNode;
    import javax.swing.tree.TreePath;
    public class TreeView{
         DefaultMutableTreeNode top;
         JTree tree ;
         Color frameColor;
         public static ImageIcon NoTSelIcon;
         public static ImageIcon SelIcon;
        public static String[] name= new String[8];
         public TreeView(Color BackColor) {
              // TODO Auto-generated constructor stub
            top =  new DefaultMutableTreeNode("Diagnostics");
            this.frameColor=BackColor;
             SelIcon = createImageIcon("../Resource/Images/Select.gif");
             if (SelIcon == null)
                 System.err.println("Tutorial icon missing; using default.");
             NoTSelIcon = createImageIcon("../Resource/Images/NotSelc.gif");
               if (NoTSelIcon == null)
                 System.err.println("Tutorial icon missing; using default.");
         public Component createTreeComponents(){
                //Create the nodes.
                 createNodes(top);
            //Create a tree that allows one selection at a time.
            tree = new JTree(top);
            //TREE LISTENERS
            //Treeselction listener
            Handler hObject = new Handler();
            tree.addTreeSelectionListener(hObject);
           //Tree expand/collapse listener
            HandlerExpansionListener hObjectExpan = new HandlerExpansionListener();
            tree.addTreeExpansionListener(hObjectExpan);
    //       tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
            //set tree background
            tree.setBackground(frameColor);
             tree.setCellRenderer(new OverrideTreeCellRenderer(frameColor,SelIcon,NoTSelIcon));
            return tree;
          private void createNodes(DefaultMutableTreeNode top) {
                 DefaultMutableTreeNode category = null;
                 DefaultMutableTreeNode SubCategory = null;
                 DefaultMutableTreeNode SubCategoryBasee = null;
                 DefaultMutableTreeNode SubSubCategoryBasee = null;
                 category = new DefaultMutableTreeNode("Dfe");
                 top.add(category);
                 //Sub test visible
                 SubCategory = new DefaultMutableTreeNode("Test Visible");
                 category.add(SubCategory);
                 SubCategory.add(new DefaultMutableTreeNode("Son 1"));
                 SubCategory.add(new DefaultMutableTreeNode("Son 2"));
                 SubSubCategoryBasee = new DefaultMutableTreeNode("Test Base");
                 SubSubCategoryBasee.add(new DefaultMutableTreeNode("Grandson 1"));
                 SubSubCategoryBasee.add(new DefaultMutableTreeNode("Grandson 2"));
                 SubCategory.add(SubSubCategoryBasee);
          class Handler implements TreeSelectionListener {
                   public void valueChanged(TreeSelectionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("treeSelect event ");
                        TreePath trph;
                        trph=arg0.getNewLeadSelectionPath();
                        int count=trph.getPathCount();
                        DefaultMutableTreeNode Selnode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
                        String Name = (String)Selnode.getUserObject();
                        setSelected(Selnode,true);
                        int number_ofnodes=getNodeCountBelow((TreeModel)tree.getModel() , Selnode, false);
                        System.out.println("The Number of nodes under "+Name+"="+number_ofnodes);
                        tree.setCellRenderer(new IconRenderer(SelIcon,NoTSelIcon,frameColor));
          class HandlerExpansionListener implements TreeExpansionListener {
                   public void valueChanged(TreeSelectionEvent arg0) {
                        // TODO Auto-generated method stub
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode)  tree.getLastSelectedPathComponent();
                        if (node == null) return;
                      }     // The inner class
                   public void treeCollapsed(TreeExpansionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("treeCollapsed event ");
                   public void treeExpanded(TreeExpansionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("treeExpanded event ");
          /** Returns an ImageIcon, or null if the path was invalid. */
             protected static ImageIcon createImageIcon(String path) {
                  //ImageIcon imcon= new ImageIcon(path);
                  //return imcon;
                 java.net.URL imgURL = TreeView.class.getResource(path);
                 if (imgURL != null) {
                     return new ImageIcon(imgURL);
                 } else {
                     System.err.println("Couldn't find file: " + path);
                     return null;
             DefaultMutableTreeNode newnode;
             public void setSelected(DefaultMutableTreeNode Selnode ,boolean isSelected)
                    Enumeration Enchilds=Selnode.children();//ENUMRATE ALL CHILDS FOR THIS NODE
                 if (Enchilds != null)
                      while (Enchilds.hasMoreElements())
                           newnode=(DefaultMutableTreeNode)Enchilds.nextElement();
                           String NameSel = (String)newnode.getUserObject();
                           setSelected(newnode,isSelected);
             //GETTING THE TREE DEPTH
             public int getNodeCountBelow(TreeModel model, Object node, boolean includeInitialNode)
                 int n = includeInitialNode ? 1 : 0;
                 for (int i = 0; i < model.getChildCount(node); i ++)
                     n += getNodeCountBelow(model, model.getChild(node, i), true);
                 return n;
    import java.awt.Color;
    import java.awt.Component;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    import javax.swing.Icon;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    public class IconRenderer extends DefaultTreeCellRenderer {
         private static final long serialVersionUID = 1L;
         Icon SelectedIcon;
         Icon NotSelectedIcon;
         Color BackgroundColor;
         boolean Selected=false;
         boolean Leaf=false;
         boolean IsItaChild=false;
         DefaultMutableTreeNode SelctedNode=null;
        public IconRenderer(Icon SelIcon,Icon NoTSelIcon,Color Bacground) {
             SelectedIcon = SelIcon;
             NotSelectedIcon = NoTSelIcon;
             BackgroundColor=Bacground;
             setBackgroundNonSelectionColor(BackgroundColor);
        public Component getTreeCellRendererComponent(JTree tree,Object value,boolean sel,boolean expanded,
                                                        boolean leaf,int row,boolean hasFocus)
             super.getTreeCellRendererComponent(tree, value, sel,expanded, leaf, row,hasFocus);
             Selected=sel;
             Leaf=leaf;
             DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
             String s2 = (String)node.getUserObject();
       return this;
    }my problem is :
    when i select a node the the method "getTreeCellRendererComponent"
    start to run on the entire tree from buttom to top and than from top to buttom.
    for me it waste of time because if has say 100 nodes it wont botthers me.
    but i have 20000 nodes and more its take a time.
    and for all this nodes i have to make compares.
    is there a way to force the DefaultTreeCellRenderer to not run the entire tree???
    Thanks

    You need to make sure that your TreeModel interprets your group nodes to be non-leaf nodes (one of the methods in the TreeModel interface is called isLeaf). If you are using a DefaultTreeModel with DefaultMutableTreeNode objects, you can use the askAllowsChildren property of DefaultTreeModel and the allowsChildren property of DefaultMutableTreeNode to control this. See the API for more details:
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultMutableTreeNode.html

  • Undo jtree selection

    Hi,
    I have a jtree, and after each selection a treepath is stored (in an arrayList )of the current selection.
    When I want to undo the current selection, and set the previous selection i shall have to use setSelectionPath(treePath);
    This again fires an event to valueChanged, with the result that I again get a new storage of a treepath, which I do not want, because this one is to undo the tree selectionpath, not to set another.
         public void valueChanged(final TreeSelectionEvent event) {
              final ExtendedDefaultMutableTreeNode node = (ExtendedDefaultMutableTreeNode)(event.getPath().getLastPathComponent());
              final FileNode fnode = getFileNode(node);
              explorerTree.expandPath(node.getPath());
              CProcessor.getInstance().do_it(new SetExplorerTreePath(fnode, explorerTree.getSelectionPath()));
         }This is my valuechanged method.
    CProcessor.getInstance().do_it(new SetExplorerTreePath(fnode, explorerTree.getSelectionPath()));
    this line stores the current treepath.
    Does anyone know how to solve this problem?
    greets, Sjoerd

    setSelectionPath(treePath);
    This again fires an event to valueChanged, with the
    result that I again get a new storage of a treepath,
    which I do not wantYou can temporarily remove the TreeSelectionListener:
            TreeSelectionListener listener = tree.getTreeSelectionListeners()[0];
            tree.removeTreeSelectionListener(listener);
            //TODO set new selection
            tree.addTreeSelectionListener(listener);

  • How do I highlight JTree selection ?

    Hi,
    How do you highlight the selected node in a JTree from code ?
    I am deleting a node and want to highlight the preceeding node. I select it via this code :-
    jTree.setSelectionPath( newSelectedPath);
    jTree.scrollPathToVisible( newSelectedPath);
    jTree.repaint();
    But that does not highlight the node.
    Many thanks in advance,
    Aaron

    With the Move tool selected, this seems to be the only way to enlarge a selection.
    What I'd want to do in Joshua's situation though is to draw a marquee around the clips I want to select. The inability to hold down shift or control and draw a second marquee to add more clips to a selection seems like a flaw! Is there a key combination or do I have to always select individual clips (or groups) after the initial selection?

  • Jtree selection problem.....help

    hi,
    I have a desktoppane....inside i m opening some internal frame.....
    also i have a tree class....which has any leaf name as internal frame title
    my question is ...when i selected any internal frame it should show selected leaf according to the internal frame activate title.....
    like we have in VB...when we select any form ...it select corresponding leaf also..
    i wanna do same...
    i using code alike this
    public void internalFrameActivated(InternalFrameEvent e)
                                                      DefaultMutableTreeNode dmt=new DefaultMutableTreeNode(getTitle());
                        TreePath pp=new TreePath(dmt.getPath());
                                            tree.expandPath(pp);
              tree.setSelectionPath(pp);
              tree.fireTreeExpanded(pp);*/
    but it's not showing selected leaf...even though it's getting correct path
    regards
    Tarique

    Hi Frank,
    Atlast i made it to work.
    TreePath tp = mBalanceInfoTree.getSelectionPath();
    StringTokenizer st = new StringTokenizer(tp.toString(), ",");
    String bal_Grp[] = new String[st.countTokens()];
    int count = 0;
    while (st.hasMoreElements()) {
    bal_Grp[count] = st.nextToken();
    count++;
    Thanks for your replies..
    N correct me if there is any wrong in this approach.
    Cheers
    SS

  • JTree Selection

    I know this has been posted on the forum quite a lot and I have looked for it but I have not found any answers as of yet. Here is my delima. I am trying to refresh a JTree by removing the children from the root and then adding the new data. Having saved the selected path before I refresh the tree. I attempt to set it after I have reloaded the data. What sux is that I cannot get it to select the path that I perviously saved. Here is the code sample...
    public void refreshTree(BsxJTree _thingTree){
          AdminJTreeHelper helper = new AdminJTreeHelper(  );
          LinkedHashMap _treeData = helper.getTreeStructure(  );
          TreePath path  = _thingTree.getSelectionPath();
          DefaultMutableTreeNode node = (DefaultMutableTreeNode ).getLastPathComponent(  );
          DefaultTreeModel       model =  ( DefaultTreeModel ) _thingTree.getModel(  );
          DefaultMutableTreeNode root  = ( DefaultMutableTreeNode ) model.getRoot( );
          root.removeAllChildren(  );
         //uses the LinkedHashMap to load the tree
          populateTree( _treeData, _thingTree );
          _thingTree.expandToPath( node );
    }This is a method that I have written to extend the JTree
    //I know this code below  works b/c I have tested it.
        * Expands the tree to make the node visible.  This method beefs up the
        * expandPath method in JTree where it expandeds the path to the node
        * passed to it if it is expandable.  Otherwise if the node is not
        * expadable it will expand the nodes parent so that the node is
        * visible.  The node will then beselected.
        * @param node the node to expand to
        * @return the path what was expanded. Either the nodes path or the parents
        *         path.
       public TreePath expandToPath( DefaultMutableTreeNode node )
          TreePath path = new TreePath( node.getPath(  ) );
          if ( node.isLeaf(  ) )
             TreePath parentPath = path.getParentPath(  );
             expandPath( parentPath );
             setSelectionPath(path);
             return parentPath;
          else
             expandPath( path );
             setSelectionPath(path);
             return path;
       }

    for all of you that actually care... (those who are searching the forums for answers. I have created the following code which works to get the node which a userObject resides. Note this code can only be used when the JTree contains DefaultMutableTreeNodes (only nodes that a userObject can be attached).
    I use this code for refreshing a JTree and then reselecting the object that was selected prior to the refresh. Code is compilable.
    Thanks for all your help but I think I am going to award the duke dollars to my self on this one.
        * Searches the JTree for the for any UserObject that is equal to the passed
        * userObject.
        * <p>
        * <b>NOTE:</b>This only works when the tree nodes are
        * DefaultMutableTreeNodes.  Those are the only nodes that you can attach a
        * user object to.
        * </p>
        * Because most objects don't specify a  .equals(Object) method the objecs
        * are considered equal if they have the same toString() value.
        * @param userObject the object to find in the tree
        * @return the node that contains the userObject
       public DefaultMutableTreeNode findUserObject( Object userObject )
          TreeNode               root = ( TreeNode ) getModel(  ).getRoot(  );
          DefaultMutableTreeNode node = getUserObjectNode( root, userObject );
          if ( node == null )
             return null;
          else
             return node;
        * Visit all nodes in a tree and check to see if that node contains the
        * UserObject.  If the node is found return the tree path for the node.
        * @param node node to process
        * @param userObject JTree to search.
        * @return the node that contains the userObject
       private DefaultMutableTreeNode getUserObjectNode( TreeNode node,
                                                         Object userObject )
          // node is visited exactly once
          DefaultMutableTreeNode foundNode = null;
          if ( node instanceof DefaultMutableTreeNode )
             DefaultMutableTreeNode fn = ( DefaultMutableTreeNode ) node;
             String                 userObjectString = userObject.toString(  );
             String                 nodeObjectString = fn.getUserObject(  ).toString(  );
             if ( userObjectString.equals( nodeObjectString ) )
                return fn;
          if ( node.getChildCount(  ) >= 0 )
             for ( java.util.Enumeration e = node.children(  );
                      e.hasMoreElements(  ); )
                TreeNode n = ( TreeNode ) e.nextElement(  );
                foundNode = getUserObjectNode( n, userObject );
                if ( foundNode != null )
                   return foundNode;
          return null;
       }

  • JTree selection problem

    I have a problem trying to select a node of a JTree using JDK 1.3.1 and JDK 1.4 beta 3. I use a JTree with a DefaultTreeModel and DefaultMutableTreeNodes.
    Before the tree became visible it has all the nodes loaded but not visible. Then I want to select a path of the tree using a node (DefaultMutableTreeNode) but I not able to do it.
    The path isn't selected and isn't visible.
    I use the following code:
      jTree.setExpandsSelectedPaths(true)
      jTree.setSelectionPath(new TreePath(node.getPath()));
      //I've also tried with
      jTree.expandPath(new TreePath(dmtn.getPath()));Thanks.

    Fair enough. I guess I need to do a bit more reading.
    You have to create a new TreePath object because the
    getPath() method of DefaultMutableTreeNode returns an
    array of TreeNodes where as the setSelected method of
    JTree requires a TreePath object.
    Why are you creating a new path with the contents ofa
    call to getPath?
    wouldn't node.getPath() be what you want toexpend/set
    visible/scroll to etc
    try it without creating a new TreePath

  • JTree select on mouse release

    How can I force a JTree to change selection on a mouse release rather than the mouse press?
    Background - I have a component that uses a JTree as a navigation device - click on a node in the tree and the right side of the GUI shows a particular panel. Some panels allow user to drag a node from the navigation tree into the panel on the right side. The drag and drop is working fine, except that when a node in the tree is clicked, it changes which panel is showing and the place that I wanted to drag to is no longer visible.
    I've temporarily worked around it by adding a "locked" checkbox to the navigation tree, so that if the checkbox is locked then I just set the tree selection back to what it was when the selection changes. This is not very user friendly. Ideally, I'd like the selection in the tree to change only when the mouse is released. Alternately, I could live with only starting a drag when the CTRL key was pressed or something similar.

    mclabo01 wrote:
    How can I force a JTree to change selection on a mouse release rather than the mouse press?This is what I might try:
    -- use getMouseListeners to save the array of MouseListener[] to an instance field
    -- iterate over the array and removeMouseListener all of them
    -- add a single MouseListener
    ---- in mouseReleased, construct a new MouseEvent from the ME received as parameter, changing the ID from MOUSE_RELEASED to MOUSE_PRESSED
    ---- iterate over the array and invoke mousePressed on each listener with the constructed event
    May work, may not. And you may have to collect the MouseListeners after the tree is made visible.
    db
    edit It appears there's no need to modify the MouseEvent. Proof of concept (may need some tuning for different treatment of each mouse button):import java.awt.event.*;
    import javax.swing.*;
    public class MouseReleaseSelectTree {
      MouseListener[] listeners;
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new MouseReleaseSelectTree().makeUI();
      public void makeUI() {
        JTree tree = new JTree();
        listeners = tree.getMouseListeners();
        for (MouseListener listener : listeners) {
          tree.removeMouseListener(listener);
        tree.addMouseListener(new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent e) {
            for (MouseListener listener : listeners) {
              listener.mouseClicked(e);
          @Override
          public void mousePressed(MouseEvent e) {
          @Override
          public void mouseReleased(MouseEvent e) {
            for (MouseListener listener : listeners) {
              listener.mousePressed(e);//pressed);
          @Override
          public void mouseEntered(MouseEvent e) {
            for (MouseListener listener : listeners) {
              listener.mouseEntered(e);
          @Override
          public void mouseExited(MouseEvent e) {
            for (MouseListener listener : listeners) {
              listener.mouseExited(e);
        JFrame frame = new JFrame();
        frame.add(new JScrollPane(tree));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }Edited by: DarrylBurke

  • JTree image question

    I have a question about using images in a JTree.
    I have like 2 parent nodes who both have a lot of child nodes now i know how to get an image for every node but how do i get 1 image for 1 parent with all his children and another image for the other parent with his children.

    It is a programming problem because i dont know how to give echt DefaultMutableTreeNode his own picture. You should think of it like msn when you log in your contacts are in a Tree and your offline contacts have a red icon and online contacts have green one. I need to to the same for my program(chat program). But i can't figure out how but i know how to give alle the DefaultMutableTreeNode's a picture but i cant give individual one's a picture.
    I hope i cleared things up :)

  • JTree path question

    I have created a program that basically simulates single celled organisms in a random (non graphical) world, and I want to use a JTree to show the family history and allow the user to bring up an organism's stats by clicking on in the the Jtree, but I have a problem. Each organism has a unique ID number (starting at 0) and that's what I want to display on the tree. I have the code working to add the new organisms to the root, but I want them added as a child to the parent (each child has only one parent for these organisms), but I don't know how to do it. I tried using insertNodeInto but since everything after the root is dynamically generated I don't know how to identify the parent correctly (just using the ID doesn't seem to do anything). Do I need to create a method that somehow copies the entire treemodel into a collection and steps through it? I have the organisms in a collection already (an arraylist to be exact), so I could figure out the lineage by stepping through that, but then how do I build a 'selection path' object that will work to tell Java exactly where I want the child to go? Is the selection path just some kind of array, or is it even possible to build a selection path without a user clicking on a tree node? I hope you can figure out what I'm trying to say here and I appreciate any help you can give.

    Start by creating a Map that has your organisms as the key and the nodes they are in as the value. Or just let the organism include a reference to the node that contains it. Either of those would allow you to identify the TreeNode that contains a particular organism.

Maybe you are looking for

  • Problem while running the xml report in concurrent program

    Hi, In EBS r12, we have requirement to have a standard report output in excel. I got the report's xml output to create the xml template (.RTF layout) using BI Publisher. I created the .RTF layout and it works fine on my laptop using Bi Publisher.. th

  • How to edit and or remake mass amounts of PDFs

    I work for a company whose instruction manuals for over 60 different products were originally created in Adobe Indesign CS2 and were then converted to PDFs. There are simple edits and changes that need to be made to these files on a weekly bases. No

  • Why are some of the albums in my library not showing up in the cloud?

    why are some of my albums not showing up in the cloud?

  • Script for making soundclips

    is there a script anywhere that will automatically make sound clips? Im not a script writer, but it seems pretty simple... stick a disc in, and click a button and it will rip 1 minute second sound clips. It wouldn't start at the beginning, it would s

  • Is eHelp's copyrighted Javascript in Air help?

    Our software application for Linux is distributed with GNU V.2 license which is fully open-source.  However, we recently discovered that the current documentation generated by Robohelp contains some eHelp-copyrighted Javascript.  This is an issue for