How to set preference for jtree in jscrollpane

I am trying to set the preferred width for jscrollpane in borderlayout (WEST). but it does not work

Please check out my sample code.

JTree tree=new JTree(root); JScrollPane jsp=newJScrollPane(tree); jsp.setBounds(0,0,200,100); Jframe.add(jsp,BorderLayout.WEST); 

but it shows the default width.

As an alternative, I tried setting the preferred size for JTree, it works fine, but jscrollpane does not work properly. Please help me with this.

+4
source share
1 answer

It is the layout manager that determines the position of the component based on the size of the component (minimum / maximum / preferred). This way your call to setBounds will be ignored, and instead, BorderLayout will determine where it places your component.

Usually this mechanism works fine. The problem with JScrollPane is that the JScrollPane its size may not synchronize with what you want as a behavior (due to the fact that the scrollbar can have scrollbars, so it can determine its own size).

Solution: just call setPreferredSize on the JScrollPane before adding it. This is also done in the official textbook and about the only moment when I can think that it is acceptable to call this method.

+2
source

All Articles