The main, but subtle assumption here is: the layout and size are directly related to 1-to-1. This is not the case, and is a common assumption in Swing programming. Size is the result of layout and size restrictions.
Layout:
- Within the space limits you specified
- And given the components that I need to fit into this space
- Place these components in relation to each other according to the specified strategy (BoxLayout, BorderLayout, etc.).
If the LayoutManager can match the components that you provided to it, without changing the overall size of the container, it will not resize the container. On the other hand, calling pack is an explicit request to minimize the amount of space used . This is the main reason you see the results.
Some things you can try:
- Make sure you set the maximum size on your components / containers, which will force restrictions on the size of the components when re-executing the layout.
- Always call pack () as a habit
- Try some suggestions regarding common placement issues.
This is difficult with Swing because you need to understand the outline of the drawing, layout managers, and some details of the window system. When it comes to the Swing documentation (and all the methods and several different ways to do one thing), I try to read the documentation with the “don't accept anything” approach, that is, “What is the least possible thing that this documentation method implies that it can do it, "and if you do not observe additional behavior, do not be fooled into thinking that he is doing more.
Finally, I would add that the work of the LayoutManager as a whole is not to determine the size of the containers, but to place the components in some relation to each other in accordance with the layout of the strategy (this is discussed in the additional information here ). The idea is that with the correct LayoutManager, you specify the basic layout of the strategy , and as a result, when you resize the window, the LayoutManager will intelligently move components around so that your user interface continues to follow this general strategy. Thus, layouts are mainly intended for regardless of the total size of the space in which they work, so they try not to make assumptions about what kind of space is available, instead they take the size that they specify and try to do what makes sense. Unless you explicitly set size limits for your components, you cannot guarantee what size they will be.
This means that if the LayoutManager does not consider that it needs to be resized to fit its overall strategy, it will not basically resize it . On the other hand, calling pack is an explicit request to collect data and remove unnecessary space.
source share