user808066
user808066

Reputation:

How to automatically resize a JTree object?

I'm trying to get a JTree object to dynamically resize when a node is expanded. By default, the object area is constant and when expanded, the bottom section of the tree gets out of view, unless the window is resized as well. How do I fix this?

Upvotes: 3

Views: 2347

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168815

Put the JTree in a JScrollPane.


E.G. (incorporating trashgod's sage tip)

import javax.swing.*;

public class BasicTree {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JTree tree = new JTree();
            tree.setVisibleRowCount(10);

            int rows = tree.getRowCount();
            for (int row=rows-1; row>-1; row--) {
                tree.expandRow(row);
            }

            JOptionPane.showMessageDialog(
                    null,
                    new JScrollPane(tree));
        });
    }
}

Tree in scrollpane

Upvotes: 4

trashgod
trashgod

Reputation: 205775

The setVisibleRowCount() method of JTree is particularly helpful in conjunction with the JScrollPane suggested by @Andrew Thompson.

Upvotes: 3

Related Questions