I have window containing multiple panels. I don’t have access to window code. (I can modify only panel’s code.)
I removed few components from panel. Window has shrunk its size. But window is too small to display everything correctly.
I added line setPreferredSize(getPreferredSize());. Now window have right size.
What are side effects of setPreferredSize?
Edit: BorderLayout is used. Which should ignore getXXXSize(). My panel is in CENTRE. Panel which doesn’t fit the screen is on NORTH.
This is what is happening:
getPreferredSize()looks whether the size was set before. If not, the method asks the LayoutManager of the component itself (which is your JPanel) about the preferred size, which is then calculated from the components.setPreferredSize(...)then sets this value on the JPanel, memorizing it for later.getPreferredSize()method again.getPreferredSize()does not ask the JPanel’s LayoutManager, but simply returns the stored size previously set bysetPreferredSize().For width, the BorderLayout is ignoring the preferred width of the NORTH and south component, it only takes CENTER, EAST and WEST into account. (Similarly for height).I just took a look at the implementation of
BorderLayout.preferredLayoutSize(in 1.6.0_13 from Sun), and it works like this:The width is calculated as
The height is calculated as
(Each of the
width/heightare the values of thepreferredSizeof these components.)If some of the five components are missing, their height/width is not included, neither are the gaps.)
It works the same for
minimalLayoutSize, whilemaximumLayoutSizesimply returnsInteger.MAX_VALUE.So, in principle it should work out of the box.
But in general, if the layout of the window is not under your control, you should not have to worry about components not under your control being cut off 🙂