Search code examples
javaswingwidthjtreeexpand

JTree enlarges width when a node gets expanded


I've got a real hard problem with a JTree.

I've implemented a JTree with a selfwritten Model (wich is extended from TreeModel).

    fileSystemModel = new MyModel(new File(directory));
    fileTree = new JTree(fileSystemModel);
    fileTree.setEditable(true);
    fileTree.setDragEnabled(true);
    fileTree.addTreeSelectionListener(new TreeSelectionListener() {

        public void valueChanged(TreeSelectionEvent event) {
            File file = (File) fileTree.getLastSelectedPathComponent();
        }
    });

So i added it to a JPanel and this JPanel to a JFrame.

No i got this Problem: I start the Frame, and if i expand a single Node, the width of JTree is going to enlarge to the width which is needed to show the leafs.

I tried to set this:

fileTree.setMaximumSize(width, height);

But it failed and i also tried to embedd the JTree into JScrollPanel with a Maximum-Size, and this has also failed.

The JTree is still adjusting its width how many it needs.

So i tried now for two days and doesn't find anything, so i would be apprecciate if someone of you could help me.

Thanks!


Solution

  • The effect described is characteristic of the default FlowLayout of JPanel. You can see the change when you click on the left panel is this example.

    Addendum: As seen in the example, GridLayout allows the component to expand; it works particularly well with setVisibleRowCount() followed by pack().