We help IT Professionals succeed at work.

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

gdkinney_2 asked
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?
Watch Question

Mick BarryJava Developer
Top Expert 2010

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

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(){

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

    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);

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

Open in new window