We help IT Professionals succeed at work.

How do I make a my vertical scroll bars resize for my JTree?

gdkinney_2
gdkinney_2 asked
on
I have a JFrame which contains a JScrollPane which contains a JPanel has a BorderLayout and contains a JTree.  How do I make my vertical scroll bars resize as I contract and expand nodes in the JTree?
Comment
Watch Question

Mick BarryJava Developer
Top Expert 2010

Commented:
you would need to resize your panel to 'fit' the table every time a node was expanded/contracted (use a ComponentListener to detect size change in tree)
If there is just your table in the panel then an easier way would be to add the tree directly to the scroll pane
Head of SW Development
Commented:

You don't have to do any special code for that. See the code below - it is a JFrame with a scroll bar which has a panel with a tree.
The vertical scroller will resize when you colapse and expand the tree.
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;

public class ExpandTest extends JFrame {

    public ExpandTest(){
        buildUI();
        pack();
        setVisible(true);
    }

    private void buildUI(){
        DefaultMutableTreeNode node = new DefaultMutableTreeNode("abc");
        addChildren(node, true);
        JTree tree = new JTree(node);
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(tree);
        JScrollPane scroll = new JScrollPane(panel);
        add(scroll);
    }

    private void addChildren(DefaultMutableTreeNode node, boolean addMore){
        for (int i = 0; i < 10; i++){
            DefaultMutableTreeNode ch = new DefaultMutableTreeNode("abc " + i);
            if (addMore) addChildren(ch, false);
            node.add(ch);
        }
    }

    public static void main(String[] args) {
        new ExpandTest();
    }
}

Open in new window