spuas
spuas

Reputation: 1693

How to adjust a JScrollPane to its contained JTree

here I have a swing size question:

I have a JTree which is contained inside a JScrollPane (which is contained in a custom component which extends JXPanel from swingx, but I think that has nothing to do with this question).

Doesn't matter how many rows the tree has, the scrollpane is always bigger (the tree is dinamic but not designed to have many rows) but what I would like is the JScrollPane to adjust to the tree initial height and then show the vertical scroll when some of the nodes are expanded.

I have tried without setting any size at all, setting tree preferred size to null and setting scrollpane preferred size to null as well but nothing changes. I DO NOT WANT to set the size manually... Is there a way to do this?

Thanks

Upvotes: 2

Views: 8005

Answers (4)

Avalance42
Avalance42

Reputation: 1

I just encounter this issue and this is the best way to do it without specifying a size from your JTree nor your JScrollpane is to set JTree to setViewportView() method of JScrollpane.

JScrollPane scrollTree = new JScrollPane(yourJTree);
scrollTree.setViewportView(yourJTree);

I think this is the best way to do it since you don't need to specify any size of Component or get a number of rows to adjust the scrollpane.

Upvotes: 0

Catalina Island
Catalina Island

Reputation: 7126

I usually just use setVisibleRowCount().

Upvotes: 6

camickr
camickr

Reputation: 324128

JTree tree = new JTree(...)
{
    @Override
    public Dimension getPreferredScrollableViewportSize()
    {
        return getPreferredSize();
    }
};

Upvotes: 3

Denis
Denis

Reputation: 21

Try to check values of scrollPane.getHorizontalScrollBarPolicy() and scrollPane.getVerticalScrollBarPolicy(). They should be equal to JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED and JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED. Also tree preferred size should be set to null. With these two conditions your scrollbars should appear\disapper automatically (assuming you are using standard JTree and JScrollPane).

Upvotes: 0

Related Questions