I have in my program two JLists, which I put into two separate JScrollPanes, and I gave the two JScrollPanes the same preferred size. The first JScrollPane is in a JPanel with horizontal BoxLayout, which is the default layout for JPanels. The JPanel is in the NORTH area of the JFrame. As far as I can tell, it has its preferred size. The second JScrollPane is not on the JFrame together with the first JScrollPane. The second one is in a JPanel with a vertical BoxLayout. I tried putting that JPanel in different places. When it's NORTH or SOUTH, it gets its preferred height, but not its preferred width. When it's EAST or WEST, it gets its preferred width, but not its preferred height. Why can't I get the second JScrollPane to its preferred height and width, like I can with the first JScrollPane?
When it's NORTH or SOUTH, it gets its preferred height, but not its preferred width. When it's EAST or WEST, it gets its preferred width, but not its preferred height. As advertised: see the BorderLayout class api, specifically the paragraph in the comments section that appears just above the demo app image. The technique for getting these outer sections of BorderLayout to show your component at its preferredSize is to add the component to another JPanel whose layout manager respects the preferredSize of its child components. FlowLayout will do this. It also places the component up toward the top and with an empty border. GridBagLayout is another layout manager that respects the preferredSize of its children and, with the default constraints, will show the component in the center with no empty border. In the test below note the difference between the FlowLayout placement (blue and yellow) and the GridBagLayout placements. BoxLayout is a specialty layout and has additional subtleties that may require attention to get it to behave the way you want. These include alignment and size peculiarities and are outlined in the tutorial page How to Use BoxLayout. The test below attempts to get the child component to be shown at its preferredSize in different configurations.
Joined: Oct 12, 2005
Thank you. I had forgotten that the default layout for a JPanel is the FlowLayout. Now I know that FlowLayout respects preferred size, and Box Layout doesn't.