Leaf and JTree

Hi all,
I would like to ask a small question about JTree. Is there a way to not display leaf without removing them from the tree?
Actually I used a tricky whay by crating my own DefaultTreeCellRenderer and checking when it's the leaf I set the preferedSize to 0. However, by using this tricky way i have some weird behaviour with scrollPane.
Does anyone has an idea to not display leaf in a JTree?
Regards,
Raffael

Raffael wrote:
Hello,
thanks for your anserw. However, creating your own JTreeModel allow you to specify if a node is a leaf or not. But you will not being able to not draw it via the tree model or I m wrong?Your custom TreeModel will have to 'hide' the leaf nodes from objects that ask about them. Here's an example that wraps a DefaultTreeModel:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.WindowConstants;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
public class HiddenLeaves {
    HiddenLeaves() {
        JFrame f= new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode nodeA = new DefaultMutableTreeNode("Node A");
        nodeA.add(new DefaultMutableTreeNode("Leaf One"));
        nodeA.add(new DefaultMutableTreeNode("Leaf Two"));
        nodeA.add(new DefaultMutableTreeNode("Leaf Three"));
        DefaultMutableTreeNode nodeB = new DefaultMutableTreeNode("Node B");
        nodeB.add(new DefaultMutableTreeNode("Leaf Four"));
        nodeB.add(new DefaultMutableTreeNode("Leaf Five"));
        nodeB.add(new DefaultMutableTreeNode("Leaf Six"));
        root.add(nodeA);
        root.add(nodeB);
        final FilteredTreeModel model = new FilteredTreeModel(new DefaultTreeModel(root));
        final JTree tree = new JTree(model);
        f.add(new JScrollPane(tree), BorderLayout.CENTER);
        JButton b = new JButton("Toggle Leaf Display");
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                boolean visible = model.isShowingLeaves();
                model.setShowingLeaves(!visible);
                tree.repaint();
        f.add(b, BorderLayout.SOUTH);
        f.setSize(400,300);
        f.setVisible(true);
    public static void main(String[] args) {
        new HiddenLeaves();
    private static class FilteredTreeModel implements TreeModel {
        private boolean showingLeaves = true;
        private DefaultTreeModel delegate;
        public FilteredTreeModel(DefaultTreeModel delegate) {
            this.delegate = delegate;
        public void setShowingLeaves(boolean show) {
            this.showingLeaves = show;
            delegate.reload();
        public boolean isShowingLeaves() {
            return showingLeaves;
        public Object getChild(Object parent, int index) {
            Object child = delegate.getChild(parent, index);
            if (!isShowingLeaves() && delegate.isLeaf(child)) {
                child = null;
            return child;
        public int getChildCount(Object parent) {
            int count = delegate.getChildCount(parent);
            if (!showingLeaves) {
                int newCount = count;
                for (int i = 0; i < count; i++) {
                    if (delegate.isLeaf(delegate.getChild(parent, i))) {
                        newCount--;
                count = newCount;
            return count;
        public int getIndexOfChild(Object parent, Object child) {
            int index = delegate.getIndexOfChild(parent, child);
            if (!showingLeaves) {
                if (delegate.isLeaf(child)) {
                    index = -1;
            return index;
        public Object getRoot() {
            return delegate.getRoot();
        public boolean isLeaf(Object node) {
            return delegate.isLeaf(node);
        public void valueForPathChanged(TreePath path, Object newValue) {
            delegate.valueForPathChanged(path, newValue);
        public void addTreeModelListener(TreeModelListener l) {
            delegate.addTreeModelListener(l);
        public void removeTreeModelListener(TreeModelListener l) {
            delegate.removeTreeModelListener(l);
}

Similar Messages

  • Consume MouseEvent to prevent JList and JTree from receiving?!

    I have a JTree and a JList where I have made the CellRenderer so that it has a "button" area. When this button is clicked, I want something to happen. This I have achieved just nicely with a MouseListener, as per suggestion from JavaDocs.
    However, the problem is that when a click is deemed to be within the "button", I do not want the tree or list to process it anymore. But doing e.consume(), both on mousePressed or mouseClicked (though it obviously is pressed the JList and JTree themselves listen to) doesn't do jack.
    How can I achieve this functionality?

    da.futt wrote:
    stolsvik wrote:
    Okay, I managed with a hack: It is the order of listeners that's the problem: The ListUI's MouseListener is installed before mine, and hence will get the MouseEvent before me, so it has already processed it when I get it, and hence consuming it makes no difference. No. Normally, listeners are notified latest-registered to earliest-registered. I don't remember seeing an exception to that rule in the core API. well, you are both right (or wrong ;-) - the rule is: the order of listener notification is undefined, it's an implementation detail which listeners must not rely on. "Anecdotical" experience is that AWTListeners are notified first-registered-first-served, while listeners to swing specific events are notified last-registered-first-served. Below is a snippet (formulated in context of SwingX convenience classes, too lazy ...) showing that difference.
    The latter probably stems from hefty c&p of notification by walking the EventListenerList: the earliest code was implemented very near the beginning of Swing when every little drop of assumed performance optimization was squeezed, such as walking from back to front. Using EventListenerList involves lots of code duplication ... so lazy devs as we all are, simply c&p'ed that loop and just changed the concrete event type and method name. More recently, as in the we-use-all-those-nifty-cool-language-features ;-) I've seen more usage of forEach loops (f.i. in beansbinding) so notification is back to first-in-first-served :-)
    Bottom line: don't rely on any sequence - if needed, use an eventBus (or proxy or however it's called) and define the order there. Darryl's suggestion is as close as we can get in Swing (as it's not supported) but not entirely safe: there's no way to get notified when listeners are added/removed and no hook where to plug-in such a bus into the ui-delegate where it would belong.
    Cheers
    Jeanette
    // output
    02.10.2009 14:21:57 org.jdesktop.swingx.event.EventOrderCheck$1 mousePressed
    INFO: first added mouseListener
    02.10.2009 14:21:57 org.jdesktop.swingx.event.EventOrderCheck$2 mousePressed
    INFO: second added mouseListener
    02.10.2009 14:21:58 org.jdesktop.swingx.event.EventOrderCheck$4 valueChanged
    INFO: second added listSelectionListener
    02.10.2009 14:21:58 org.jdesktop.swingx.event.EventOrderCheck$3 valueChanged
    INFO: first added listSelectionListener
    // produced by
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.logging.Logger;
    import javax.swing.JList;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import org.jdesktop.swingx.InteractiveTestCase;
    import org.jdesktop.test.AncientSwingTeam;
    public class EventOrderCheck extends InteractiveTestCase {
        public void interactiveOrderAWTEvent() {
            JList list = new JList(AncientSwingTeam.createNamedColorListModel());
            MouseListener first = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    LOG.info("first added mouseListener");
            MouseListener second = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    LOG.info("second added mouseListener");
            list.addMouseListener(first);
            list.addMouseListener(second);
            ListSelectionListener firstSelection = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) return;
                    LOG.info("first added listSelectionListener");
            ListSelectionListener secondSelection = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) return;
                    LOG.info("second added listSelectionListener");
            list.addListSelectionListener(firstSelection);
            list.addListSelectionListener(secondSelection);
            showWithScrollingInFrame(list, "event order");
        @SuppressWarnings("unused")
        private static final Logger LOG = Logger.getLogger(EventOrderCheck.class
                .getName());
        public static void main(String[] args) {
            EventOrderCheck test = new EventOrderCheck();
            try {
                test.runInteractiveTests();
            } catch (Exception e) {
                e.printStackTrace();
    }

  • How do I use JPanel as a leaf in JTree ?

    Hi All,
    I am a bit of a newbie and I've been trying to change the behavior of my application.
    I have a JTree that I now want to change the rendering of a leaf to be a JPanel. The JPanel will have a couple of JButtons and some text and the user can interact with the JButtons. I was successful in creating the JPanel, adding the buttons and then making my own TreeCellRenderer. Everything displays fine, but the user can not interact with the JButtons, whenever I click on a button in the leaf, the whole leaf is highlighted - I suppose I should not be surprised because this is probably behaving just a cell in a JTree should.
    So I searched the forums and used Google and have found several examples of people using JCheckBox as nodes/leaf(s) in a JTree but none with a JPanel as a leaf. I took one of the check box demos from here ( [http://www.coderanch.com/t/330630/Swing-AWT-SWT-JFace/java/add-swing-component-tree]) and then hacked it a bit but am stuck with the following error :
    Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.JPanel
    which is pointing to the line with JPanel temp2 = (JPanel) temp.getUserObject();
    Does anyone have either some code or suggestions to accomplish a leaf as a JPanel with some buttons ?
    Thanks in advance !
    import javax.swing.*;*
    *import javax.swing.tree.*;
    import java.awt.event.*;*
    *import java.awt.*;
    public class treedemo1 extends JFrame {
        public treedemo1() {
            super("TreeDemo");
            setSize(1500, 1500);
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());
            customLeafPanel cp1 = new customLeafPanel();
            customLeafPanel cp2 = new customLeafPanel();
            customLeafPanel cp3 = new customLeafPanel();
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Query Results");
            DefaultMutableTreeNode n1 = new DefaultMutableTreeNode(cp1, false);
            DefaultMutableTreeNode n2 = new DefaultMutableTreeNode(cp2, false);
            DefaultMutableTreeNode n3 = new DefaultMutableTreeNode(cp3, false);
            root.add(n1);
            root.add(n2);
            root.add(n3);
            JTree tree = new JTree(root);
            p.add(tree, BorderLayout.NORTH);
            getContentPane().add(p);
            TestRenderer tr = new TestRenderer();
            tree.setEditable(false);
            tree.setCellRenderer(tr);
        public class customLeafPanel extends JPanel {
            public customLeafPanel() {
                JPanel clpPanel = new JPanel();
                JButton helloJButton = new JButton("Hello");
                this.add(helloJButton);
        public class TestRenderer implements TreeCellRenderer {
            transient protected Icon closedIcon;
            transient protected Icon openIcon;
            public TestRenderer() {
            public Component getTreeCellRendererComponent(JTree tree,
                    Object value,
                    boolean selected,
                    boolean expanded,
                    boolean leaf,
                    int row,
                    boolean hasFocus) {
                DefaultMutableTreeNode temp = (DefaultMutableTreeNode) value;
                JPanel temp2 = (JPanel) temp.getUserObject();
                return temp2;
            public void setClosedIcon(Icon newIcon) {
                closedIcon = newIcon;
            public void setOpenIcon(Icon newIcon) {
                openIcon = newIcon;
        public static void main(String args[]) {
            JFrame frame = new treedemo1();
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            frame.pack();
            frame.setVisible(true);
    }

    Thank you TBM and DB for your replies ! Adding TBM's code does indeed fix the JPanel issue and as TBM indicated this does not actually solve my ultimate problem (Can I give you each 1/2 the Duke points?)
    As a newbie, I am still learning and DB pointed out that "You can however interact with an editor". So after reading the suggested tutorials and looking back at the example code that I hacked. I added the cellEditor back in and it WORKS ! Its funny, I deleted that bits of code from the example, assuming the cellEditor allows you to "edit" (ie change), not interact with it (symantics I guess)
    Thanks again guys for pointing this newbie in the right direction. Frankly I am somewhat surprised that I could finally begin to read and understand what the tutorial and suggestions are telling me ! What is one step up from a newbie ?
    unfortunately I can not post the code because the length of the message is > 5000 :(

  • Having trouble with JCheckBox and JTree

    I am trying to render the JTree to display JCheckBox's instead of just ordinary JLabels.
    It's fine, compiles, and when you view it it looks normal, until you try to check one.
    You can't check it at all.
    What am i doing wrong with this?
    Thanks

    OK, here it is...
    public class EmotiTreeCellRenderer extends DefaultTreeCellRenderer {
         protected JCheckBox label;
         public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
              if ( value instanceof DefaultMutableTreeNode ) {
                   label = new JCheckBox();
                   label.setOpaque( false );
                   if ( selected && hasFocus ) {
                        label.setForeground( Color.blue );
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
                   Object userObject = node.getUserObject();
                   if ( userObject instanceof Emoticon ) {
                        Emoticon emoticon = (Emoticon)userObject;
                        String icon = emoticon.getIconKeys();
                        try {
                             label.setText( "<html><body><img src=\"" + new File( emoticon.getRealPathToEmoticon() ).toURL().toString() + "\" alt=\"" + parseAlt( icon ) + "\"> " + parseAlt( icon ) + "</body></html>" );
                        } catch ( MalformedURLException mfe ) {
                             label.setText( "<html><body>" + parseAlt( icon ) + "</body></html>" );
                        return label;
                   } else if ( userObject instanceof EmotiPack ) {
                        EmotiPack pack = (EmotiPack)userObject;
                        label.setText( pack.getName() );
                        return label;
              return super.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus );
         protected String parseAlt(String html) {
              return html.replace( "<", "<" ).replace( ">", ">" ).replace( "\"", "&#34;" );
    }

  • Creating a JTable as a leaf for JTree

    Is it possible to create a JTable as leaf node of a JTree..?
    I used treecellrenderer which returns JTable as component.. but i'm getting a single row of table in my tree..? How can i solve this..?

    bbritta,
    Thanks a lot.. for u'r support. But actually i don't want to have some kind of explorer type interface with a tree on the left side of a panel & a TABLE . I want to have a JTable as a leaf node in JTree. I mean i need JTable as node for Jtree.. But still teh code u suggested make some sense.. i will give a try.. Thanks..
    gussev,
    U got my problem..!
    "that is possible, at the beginning of the next month, even at the end of this I'm going to release several JavaBeans and "JTable as a node for a JTree" bean would be available. I'll send a message to forum. "
    I'm eagerly waiting for u'r message..
    Thanks
    Saran

  • Any component as leaf for JTree problems

    hi,
    I'm trying to get arbitary components as leaves in a JTree and it looks like its very nearly there, but there are two (related?) problems.
    1) If you click around on the top 3 tree components then it gets stuck in a loop of rendering and causes a stack exception to be thrown.
    2) For the embedded JTree component, expanding its nodes doesn't update the parent tree
    both may be because current the row height is set at the wrong time (in the TreeCellRenderer)
    any help would be really appreciated!
    thanks,
    asjf
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import java.util.*;
    public class ComponentTree
         public static void main(String args[])
              try{(new UIManager()).setLookAndFeel((new UIManager()).getSystemLookAndFeelClassName());}
              catch(Exception e){}
              DefaultMutableTreeNode c0 = new DefaultMutableTreeNode(new JButton("root"));
              DefaultMutableTreeNode c1 = new DefaultMutableTreeNode(new JButton("c1"));
              DefaultMutableTreeNode c2 = new DefaultMutableTreeNode(new JList(new Object [] {"A","B","C"}));
              DefaultMutableTreeNode c3 = new DefaultMutableTreeNode(new JTable(new Object [][] {{"Active","true"},{"User","root"}}, new Object [] {"Name","Value"}));
              DefaultMutableTreeNode c4 = new DefaultMutableTreeNode(new JTree());
              DefaultMutableTreeNode c5 = new DefaultMutableTreeNode(new JList(new Object [] {"D","E","F"}));
              DefaultMutableTreeNode c6 = new DefaultMutableTreeNode(new JCheckBox("Active",true));
              DefaultTreeModel dtm = new DefaultTreeModel(c0);
                   dtm.insertNodeInto(c6,c0,0);
                   dtm.insertNodeInto(c1,c0,0);
                   dtm.insertNodeInto(c2,c0,0);
                   dtm.insertNodeInto(c5,c2,0);
                   dtm.insertNodeInto(c3,c1,0);
                   dtm.insertNodeInto(c4,c3,0);
              JTree tree = new JTree(dtm);
                   tree.setEditable(true);
                   tree.setCellRenderer(new DefaultTreeCellRenderer()
                        public Component getTreeCellRendererComponent(     JTree tree,     Object value, boolean isSelected, boolean expanded, boolean leaf, int row, boolean hasFocus)
                             System.out.println("Render row "+row);
                             Component c = (Component) ((DefaultMutableTreeNode) value).getUserObject();
                             if(c instanceof JCheckBox)
                                  c.setBackground(UIManager.getColor("Tree.textBackground"));
                             tree.setRowHeight(c.getHeight());                    
                             return c;     
                   tree.setCellEditor(new DefaultTreeCellEditor(tree,(DefaultTreeCellRenderer)tree.getCellRenderer())
                        public boolean isCellEditable(EventObject evt){return true;}
                        public Component getTreeCellEditorComponent(     JTree tree,     Object value, boolean isSelected, boolean expanded, boolean leaf, int row)
                             return (Component) ((DefaultMutableTreeNode) value).getUserObject();
              JFrame frame = new JFrame("ComponentTree");
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame.getContentPane().add(tree);     
                   frame.pack();
                   frame.show();
    }

    thanks!
    this seems an awful lot of code to get this working - it should be possible to have a single CellEditor/Renderer??
    also running the code - its very hard to select checkbox items, and the JLists seem to disable themselves when the main tree updates?
    its also not general to any Component (?) (although we probably only want JComponent) so we can't add a JTree as a leaf?
    I'm guessing there is a simpler way to get this working?

  • Problem with JPopupMenu and JTree

    Hi,
    Is there any way to have different JPopupMenu for every node.
    When I right click on the treenode there is popup menu have a "*JCheckBoxMenuItem*". By default the value of that checkbox is false. Now when i try to right click on a particular node and select the checkbox the selected value gets applied to rest of all nodes also.
    How can i just set the value of the checkbox to one perticular node.
    my code is
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress=new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ie) {
                            if(compress.getState()){
                                 compress.setState(true);
                                    System.out.println("compress clicked");
                            else{
                                 compress.setState(false);
                                    System.out.println("uncompress");
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if(path!=null && path==tree.getAnchorSelectionPath()) {
            super.show(c, x, y);
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }Please help me as soon as possible.
    Thanks.
    Edited by: Kavita_S on Apr 23, 2009 11:49 PM

    Hi,
    Do you know this link?
    [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html]
    Please help me as soon as possible.Sorry that I'm not good at English, I don't understand what you mean.
    Anyway, here's a quick example:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest3 {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress = new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {
              if (compress.getState()) {
                System.out.println("compress clicked");
                setSelectedPath(path, true);
              } else {
                System.out.println("uncompress");
                setSelectedPath(path, false);
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if (path!=null && path==tree.getAnchorSelectionPath()) {
            compress.setState(isSelectedPath(path));
            super.show(c, x, y);
      class MyData {
        public boolean flag;
        public String name;
        public MyData(String name, boolean flag) {
          this.name = name;
          this.flag = flag;
        @Override public String toString() {
          return name;
      //private Set<TreePath> selectedPath = new HashSet<TreePath>();
      private void setSelectedPath(TreePath p, boolean flag) {
        //if (flag) selectedPath.add(p);
        //else    selectedPath.remove(p);
        DefaultMutableTreeNode node =
              (DefaultMutableTreeNode)p.getLastPathComponent();
        Object o = node.getUserObject();
        if (o instanceof MyData) {
          ((MyData)o).flag = flag;
        } else {
          node.setUserObject(new MyData(o.toString(), flag));
      private boolean isSelectedPath(TreePath p) {
        //return selectedPath.contains(p);
        Object o =
              ((DefaultMutableTreeNode)p.getLastPathComponent()).getUserObject();
        return (o instanceof MyData)?((MyData)o).flag:false;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest3().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

  • JSplitPane, JScrollPane and JTree resizing

    Hi,
    In a JSplitPane, I have, in the left part, a JScrollPane, containing a JTree and, in the right part, I have an other panel.
    When I click on different nodes in the JTree, the width of the left part changes, so the JSplitPane separator moves. How to avoid that ? I would prefer a scrolling move inside the JScrollPane !
    I am using JDK 1.3
    Thanks
    Olivier Scalbert

    Try to define the JScrollPane as
    public JScrollPane(Component view, int vsbPolicy, int hsbPolicy)
    Use vsbPolicy and hsbPolicy like the VERTICAL_SCROLLBAR_AS_NEEDED
    HORIZONTAL_SCROLLBAR_AS_NEEDED respectively.
    Then define the setPreferredSize to your JScrollPane. This preferredSize must be smaller than the size of the Component view if you want to see the ScrollBar.
    By the way, when you define your JSplitPane have to define the setOneTouchExpandable(true);?

  • Vector and Jtree 4Duke

    hi
    i am having poblem with my jtree as i am not able to show the object in my vector as a different node
    {each object is node of my tree}
    unfortunately they all appear flat in the root, and in sequence{as one node} ??
    i have done everything but still no answer??
    thanks in advance for any solution
    public class Gui extends JFrame
    {  Vector root = new Vector();
    public JTree theTree ;
    public SERGui( )
    System.out.println(root.size());//root vector is empty
    roott = new DefaultMutableTreeNode (root);
    model = new DefaultTreeModel (roott) ;
    theTree = new JTree (model);      
    public Vector addOne(String newString)
    if (!root.contains(getQuery))
               root.add(newString);
    model.reload();
    // //updateTree(); i also try this method whiich does not work
    return root;
    public void updateTree(){
    DefaultMutableTreeNode v = (DefaultMutableTreeNode)theTree.getModel().getRoot();
    for(int i=0;i<root.size();i++)
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode)root.elementAt(i);
                   roott.add(node);
    ((DefaultTreeModel)theTree.getModel()).reload(v);
    //DefaultMutableTreeNode node = null;
    print_vector(root);
      //root.clear();
         }and my other class
    where i call this methos is as follow
    Class Search()
    public void countWord(String newString)
    {Gui.addOne(newString);
    }}

    You are passing a Vector into the constructor of the DefaultMutableTreeNode to create the root of your tree. The DefaultMutableTreeNode will use this object's string representation (by calling toString on whatever object you pass in its constructor) as the name of the tree node. So basically you will see the entire contents of the vector as the name of your root node.
    You need to traverse your vector, and use each element to create a DefaultMutableTreeNode and add it to your root node.
    here is the modified code
    public class Gui extends JFrame {
    private Vector rootVector = new Vector();
    private JTree theTree;
    private DefaultMutableTreeNode rootNode;
    private DefaultTreeModel model;
    public Gui() {
    System.out.println(rootVector.size());
    //root vector is empty
    rootNode = new DefaultMutableTreeNode("Root");
    model = new DefaultTreeModel(rootNode);
    theTree = new JTree(model);
    public Vector addOne(String newString) {
    if (!rootVector.contains(newString)) {
    rootVector.add(newString);
    updateTree();
    return rootVector;
    public void updateTree() {
    rootNode.removeAllChildren();
    for (int i = 0; i < rootVector.size(); i++) {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(
    rootVector.elementAt(i));
    rootNode.add(node);
    ((DefaultTreeModel) theTree.getModel()).reload(rootNode);
    Hemant Mahidhara

  • JSplitPane and Jtree

    Hi all,
    in my window I've got a JSplitPane with the left component that is a JScrollPane with a Jtree (used as a menu), while in the right side a customized JPanel that changes depending on the selection in the tree on the left.
    My panels are initially created as follows:
         this.splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
         this.splitter.setOneTouchExpandable(true);
    JScrollPane leftPanel = new JScrollPane( this.menuTree );
              leftPanel.setMinimumSize( new Dimension(300,300) );     
              leftPanel.setMaximumSize(leftPanel.getMinimumSize());
              // add the leftt and right panels
              this.splitter.setLeftComponent( leftPanel );
              this.imagePanel = new ImagePanel(ComponentBuilder.getLogoPath());
              this.rightPanel = this.imagePanel;
              this.splitter.setRightComponent(this.rightPanel);
              // add the splitter to myself
              this.add(new JScrollPane(this.splitter));where the imagepanel is a working panel that shows the project logo. Now what happens is that:
    1) the logo is cutted to a size I don't know how is calculated, since the image panel is working fine (if I place on a separate window I can see the image right)
    2) most important when a user selects something in the tree on the left panel, so the right panel changes, the left panel is moved around the window depending on the size of the right panel.
    Is it possible to fix the left panel not only as size, but also in the position of the window, thus the remaining part of the window will be occupied by the right panel without moving the left one? In my frame I'm using a BorderLayout, and the panel containing the splitpane is set at the center (no components on the right and on the left).
    Thanks,
    Luca

    Thanks for your reply, but the only thing I noticed is that the code you're showing works a little more with sizes, that is something I've already tried. By the way, the following is a running example that loads a tree/menu and the logo.png image.
    Any idea about its behaviour?
    Thanks,
    Luca
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.awt.image.*;
    class ImagePanel extends JPanel implements ImageObserver
         * The image to display
        protected Image image=null;
         * This flag indicates if the image is complete or not.
        protected boolean isComplete=false;
         * The dimension of the panel.
        protected int width=0,height=0;
         * This is the message to display during loading.
        protected String message="Loading...";
         * Default constructor.
         * @param image the image object.
        public ImagePanel(Image image)
              super();
              this.image=image;
         * Overloaded constructor. It try to load the image itself. You should use
         * this to avoid image flicking problems. This method use all the
         * capabilities of the ImageObserver.
         * @param image the image file name
        public ImagePanel(String image) {
              super();
              /* now load the image */
              Toolkit tk=Toolkit.getDefaultToolkit();
              this.image=tk.getImage(image);
              /* use the media tracker to wait untill the image is not loaded */
              try{
                  MediaTracker tracker=new MediaTracker(this);
                  tracker.addImage(this.image,0);
                  tracker.waitForID(0);
                  this.isComplete=true;
                  /* now that the image is fully loaded I need to resize the panel to
                  the size of the image */
                  this.width=this.image.getWidth(this);
                  this.height=this.image.getHeight(this);
                  this.setSize(width,height);
                  this.setMinimumSize(getSize());
                  this.setMaximumSize(getSize());
                  this.setVisible(true);
              catch(InterruptedException e){
                  this.message="Exception during loading process!";
                  this.isComplete=false;
         * Draw the image.
        public void paint(Graphics device)   {
              super.paint(device);
              if(this.isComplete==true)     {
                  device.drawImage(this.image,0,0,this.width,this.height,this);
              else     {
                  device.setColor(Color.RED);
                  device.drawString(this.message,20,20);
         * The update image method. This method is called for every update and or
         * error.
        public boolean imageUpdate(Image image,int infoFlags, int x, int y,
                        int width, int height)
              if((infoFlags & ALLBITS)==0)
                  /* the image is complete */
                  this.isComplete=true;
                  repaint();
                  this.setVisible(true);
                  return false;
              else
              if((infoFlags & ERROR)==0 || (infoFlags & ABORT)==0 )
                  /* error or abort */
                  this.isComplete=false;
                  this.message="Error during load process (or abort)";
                  this.repaint();
                  return true;
              else
              if((infoFlags & SOMEBITS)==0)
                  /* some other data loaded, show the loading process percent */
                  int originalWidth=this.image.getWidth(this);
                  int originalHeight=this.image.getHeight(this);
                  int currentWidth=image.getWidth(this);
                  int currentHeight=image.getHeight(this);
                  /* now calculate the total of pixels */
                  long originalTotal=originalWidth*originalHeight;
                  long currentTotal=currentWidth*currentHeight;
                  /* now calculate the percent */
                  float percent=(float)currentTotal/(float)originalTotal *100;
                  /* set the string */
                  this.message="Loading progress: "+(int)percent+" % done";
                  this.repaint();
                  return true;
              return true;
    public class MainPanel extends JPanel {
          * The split pane used for this panel.
         protected JSplitPane splitter = null;
          * The menu tree of this panel.
         protected JTree menuTree = null;
          * The parentFrame frame of this panel
         protected JFrame parentFrame = null;
          * The panel on the right of the window.
         protected JComponent rightPanel = null;
          * The menuTreeRoot node of the menu.
         protected DefaultMutableTreeNode menuTreeRoot = null;
          * The action menu of the JFrame that contains this panel. Such menu is changed depending on the panel
          * shown on the right panel.
         protected JMenu actionMenu = null;
          * The image panel with the image of the logo.
         protected ImagePanel imagePanel = null;
         public final String ROOT_STRING = "Gestione delle risorse umane";
         public final String LEVEL1A_STRING = "Parametrizzazione";
         public final String LEVEL2AA_STRING = "Competenze & Famiglie di competenze";
         public final String LEVEL2AB_STRING = "Gestione dei ruoli";
         public final String LEVEL2AC_STRING = "Associazione ruolo-competenza";
         public final String LEVEL1B_STRING   = "Varie";
         public final String LEVEL2BB_STRING = "Province";
         public final String LEVEL2BC_STRING = "Citta'";
         public final String LEVEL2BD_STRING = "Livelli di istruzione";
         public final String LEVEL2BE_STRING = "Livelli di competenza";
         public final String LEVEL3A_STRING   = "Personale";
         public final String LEVEL3AA_STRING = "Anagrafica di base";
         public final String LEVEL3AB_STRING  = "Ruoli, Competenze e Gradi di Istruzione";
         public final String LEVEL3AC_STRING  = "Storia delle valutazioni delle competenze";
         public final String LEVEL3AD_STRING  = "Valutazione";
          * Default constructor.
          * @param parentFrame the jframe that contains this panel
         public MainPanel(JFrame parent, JMenu actionMenu){
              super();
              this.parentFrame = parent;
              this.initGUI();
              this.actionMenu = actionMenu;
          * Shows the components on the main panel.
         public synchronized void initGUI(){
              // create the split pane
              this.splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
              this.splitter.setOneTouchExpandable(true);
              //this.splitter.setResizeWeight(0);                    // the right panel gets all the extra space
              // create the left panel with the tree
              DefaultMutableTreeNode root = new DefaultMutableTreeNode(ROOT_STRING);
                   DefaultMutableTreeNode level1a = new DefaultMutableTreeNode(LEVEL1A_STRING);
                        ContainerTreeNode level2aa = new ContainerTreeNode(LEVEL2AA_STRING);     // skills and families
                   DefaultMutableTreeNode level2ab = new DefaultMutableTreeNode(LEVEL2AB_STRING);
                        DefaultMutableTreeNode level2ac = new DefaultMutableTreeNode(LEVEL2AC_STRING);
                   DefaultMutableTreeNode level1b = new DefaultMutableTreeNode(LEVEL1B_STRING);
                        DefaultMutableTreeNode level2bb = new DefaultMutableTreeNode(LEVEL2BB_STRING);
                        DefaultMutableTreeNode level2bc = new DefaultMutableTreeNode(LEVEL2BC_STRING);
                        DefaultMutableTreeNode level2bd = new DefaultMutableTreeNode(LEVEL2BD_STRING);
                        DefaultMutableTreeNode level2be = new DefaultMutableTreeNode(LEVEL2BE_STRING);
                   DefaultMutableTreeNode level3a = new DefaultMutableTreeNode(LEVEL3A_STRING);
                        DefaultMutableTreeNode level3aa = new DefaultMutableTreeNode(LEVEL3AA_STRING);
                        DefaultMutableTreeNode level3ab = new DefaultMutableTreeNode(LEVEL3AB_STRING);
                        DefaultMutableTreeNode level3ac = new DefaultMutableTreeNode(LEVEL3AC_STRING);
                        DefaultMutableTreeNode level3ad = new DefaultMutableTreeNode(LEVEL3AD_STRING);
              // create the tree
              this.menuTreeRoot = root;
              level2ab.add(level2ac);
              level1a.add(level2aa);
              level1b.add(level2bc);
              level1b.add(level2bb);
              level1b.add(level2bd);
              level1b.add(level2be);
              level3a.add(level3aa);
              level3a.add(level3ab);
              level3a.add(level3ac);
              level3a.add(level3ad);
              root.add(level3a);
              root.add(level2ab);
              root.add(level1a);
              root.add(level1b);
              this.menuTree = new JTree(root);
              this.menuTree.setSize(200,200);
              JScrollPane leftPanel = new JScrollPane( this.menuTree );
              leftPanel.setMinimumSize( new Dimension(300,300) );     // it does not affects the dimension, but avoid to resize the left panel
              leftPanel.setMaximumSize(leftPanel.getMinimumSize());
              // add the leftt and right panels
              this.splitter.setLeftComponent( leftPanel );
              this.imagePanel = new ImagePanel("logo.png");
              this.rightPanel = this.imagePanel;
              this.rightPanel.setSize(400,400);
              this.splitter.setRightComponent(this.rightPanel);
              // add the splitter to myself
              this.add(new JScrollPane(this.splitter));
         public static void main(String argv[]){
             JFrame f = new JFrame();
             f.setSize(400,400);
             f.add(new MainPanel(f,null));
             f.setVisible(true);
    }

  • JList and JTree

    Hello,
    I have a list of servers in a JList( is a seperate class) and when i am selecting a server name from the JList i am calling this value in my main class and I am trying to use this selected value from the Jlist to create a new JTree node but the value is not being displayed as a node.
    Any body having ideas as to why?
    Reg,
    suri

    Hello,
    Thanks for ur replies. I have tried the following way but still no results the node is not appearing in the JTree.
    Here logon(this is a listBox class and contains a JList with a list of server names)
    and root1 is the parent .
    DefaultMutableTreeNode new1 = new DefaultMutableTreeNode(logon.getValue(), true);
         int childCnt = root1.getChildCount();
         treeModel.insertNodeInto(new1, root1, childCnt);
    treeModel.reload(new1);
    treeModel.nodeStructureChanged(new1);
    JTree1.revalidate();
    JPanel1.revalidate();
    Any body any ideas .
    Thanks,
    reg,
    suri

  • ZipFiles and JTree

    I am developing a tool which compares to source zip files and generate report. I got stuck in the middle of the project.
    Do anybody help in extracting z zip file and displaying the whole contents in zip file using JTree format. I was able to extract the contents from the zip file but couldn't display those contents using JTree.

    Follow the bouncing link. As always Google is your friend.
    http://www.google.com/search?hl=en&q=Java+%2B+extracting+zip+file
    Cheers,
    PS

  • JEditorPane and JTree

    Hi,
    I have a tree that lists all objects and I want to do some kind of search feature. Results would be displayed in JEditorPane but I don't know anything about that. In JTree there is TreeSelectionListener (method valueChanged) and that has the functionality I need to have on JEditorPane but I don't know if this is possible?
    Any advices please?

    Hi,
    I have a tree that lists all objects and I want to do some kind of search feature. Results would be displayed in JEditorPane but I don't know anything about that. In JTree there is TreeSelectionListener (method valueChanged) and that has the functionality I need to have on JEditorPane but I don't know if this is possible?
    Any advices please?

  • Database and JTree

    I have table in access entitled employees and wish to generate a JTree to show the organizational heirarchy of the company. I feel like I've followed the steps properly but the Jtrees either don't work or they work with the wrong data.
    "Perform a query to obtain the name of the employee. If you are at the root node (level 0), just change the value of the current node to the name you got from the query, otherwise, create a child node and set its value to be that name. Perform another query to get the employee IDs of all the employees whose manager is the current employee. Loop through this result set, recursively calling the method for each of the employees in the resultset from step (4)."[]
        public static void generateTree(DefaultMutableTreeNode node, int id, int level){
            DbSource dbs = new DbSource("EmpDb");
            if (dbs.isConnected()){
             boolean success = dbs.processQuery("select firstname, lastname from employees", false);
             if(success){
                 while(dbs.nextRecord()){
                  DefaultMutableTreeNode newNode;
                    if (level==0){
                        node.setUserObject(dbs.getField(1)+ " " + dbs.getField(2));
                        newNode=node;
                    else{
                        newNode = new DefaultMutableTreeNode(dbs.getField(1) + " " + dbs.getField(2));
                        node.add(newNode);               
                 boolean success2 = dbs.processQuery("select employeeid from employees where " + id+ " = manager", false);
                 if (success2){
                 while (dbs.nextRecord()){
                      generateTree(newNode, id, level+1);                      
        }Any quick hints are appreciated.

    Well, you didn't say what was wrong with the result of this. But that doesn't matter because I can see a lot of things wrong with the code.
    First you don't have anything that gets the level-zero node. (The president of the company or whatever that is.) You should do this outside the recursively-called method and create a node that contains that person's name. Then call the method, passing it that node.
    Second, in your posted code you have something that reads the entire file at every level. What's that for?
    Third, the last four lines of that method look like the actual code you need: get the employees who report to the manager in the current node. However you need something that creates a new node for each of those employees and adds it to the manager node.
    Fourth, you don't seem to use that "level" parameter anywhere. I don't think you have any need for it.
    Fifth, and I don't know if this is a problem, you will need to be able to process several DbSource objects simultaneously. Possibly you can, but it's possible to code that sort of thing so that you can't.

  • Xml to JTree, and JTree node to html file.

    I have been trying to figure out a way to do this and I think I have a solution, but I am not sure how to structure the application and methods.
    working with BorderLayout Panel p, JSplitPane split, JTree tree, and JEditorPane rpane
    1st. My JSplitpane is divided with the tree, and rpane. The tree is on the left, and the rpane is on the right. both of these are then added to the Panel p
    2. I will create a method that will read through a modules.xml file, and create a JTree - tree. When you click on the node element it's information is displayed in the right pane - rpane.
    The Problem. I think it would take to long to create the html file on the fly each when I click on each individual node.
    So my idea is to create the html files from many xml files when I run the program. I can then just load the html file when I click on each individual node.
    This means alot of heavy processing in the front end, and everything will be static, but it will be faster when the user is in the program.
    Problem. How do I associate each node element with the correct html file?
    The Tree elements are always the same, but I can have 1 or many modules.
    Here is an example:
    <device>  // - root
       <module1>
          <Status>
             <Network></Network>
             <Device></Device>
             <Chassis></Chassis>
             <Resources></Resources>
          </Status>
          <ProjMngt></ProjMngt>
          <ProjEdit></ProjEdit>
          <Admin>
             <admNetwork></admNetwork>
             <admUsers></admUsers>
          </Admin>
          <Logging></Logging>
       </Module1>
       ...  Now I can have 1 or many Modules depending on what the xml file  has in it.
       <Module*n>
    </device>Other problems. Some of the information I want to store as a sortable Table, but I cannot seem to get any of the sort methods to work. They work if I just open a browser, and run the html file, but if I stick the html file into the JEditorPane it does not work? - any suggestions?
    Also, can I pass a JTabbebPane to the JEditorPane, or can I create a tabbed pane in html that will do the same thing.
    I am working with a very small device. It does not have a web application container like Tomcat on it. Just Apache, and Java. That is why I am using Swing.

    Using 'productAttribute/text()' gets you all three productAttribute nodes and then grabs all the text under that node. It simply concatenates together all the text under the desired node, hence the results you are seeing. If you want to get the text for each child node separately, then you need to do something like (assumes 10.2.x.x or greater)
    WITH your_table AS (SELECT
    '<root><productAttribute>
    <name>Baiying_attr_03</name>
    <required>false</required>
    </productAttribute>
    <productAttribute>
    <name>Baiying_attr_04</name>
    <required>false</required>
    </productAttribute>
    <productAttribute>
    <name>Baiying_attr_05</name>
    <required>false</required>
    </productAttribute></root>' xmldata
    FROM DUAL)
    -- Above simulates your DB table as I don't have it
    -- You only care about the following
    SELECT xt.*
      FROM your_table yt,
           XMLTable('/root/productAttribute'
                    PASSING XMLTYPE(yt.xmldata)
                    COLUMNS
                    prd_nm   VARCHAR2(30)  PATH 'name',
                    prod_rqd VARCHAR2(5)   PATH 'required') xt;Note: I added a <root> node as you had just provided a XML fragment. You will need to adjust accordingly.
    The above produces
    PRD_NM                         PROD_RQD
    Baiying_attr_03                false
    Baiying_attr_04                false
    Baiying_attr_05                false

Maybe you are looking for

  • OAS 4.0.8 PL/SQL Catridge exception ORA-6502 (Numeric or value error)

    Hello, Out product is using OAS 4.0.8.2 on UNIX running SOlaris. We are using Oracles Web Toolkit for application development and presentation. I am basically trying to fill up some HTML form fields and calling an HTTP post procedure in response to a

  • Problem with surfboard seg6580 & Airport Express (latest gen)

    I can wiressly connect and iPad and Apple TV (latest models) to the internet but I cant to the same with the Airport Express.

  • Network at Home

    This may be the simplest question but I hope I can get some help. I will put it in very simple terms as well. I have one of the new iMac's 10.5.3 and my wife has a powerbook G4 with Tiger. On the Leopard video they showed how you can access other sha

  • Calling dll file to control a third party board from PC Control.

    Hi there, I have this hawkeye stepper motor control board from PC control company.  It comes with a software written by the company  which is in DLL format. I would like to call the DLL file in labview and be able to do further programming on it usin

  • Drag Zones with multiple pictures - How to get them to play?

    I have struggled with this program for hours. In previous posting from 2005 people say there was a "bug" in the program so multiple pictures in drag zones would not play? Anyone know if this was fixed? Sure won't play for me and instruction manuals s