Whenever I look for solutions related to layouts, I come across people who advise against using the setMinimumSize(), setPreferredSize() and setMaximumSize() methods.
The typical argument is, that a correct LayoutManager should be used instead.
My understanding is that the LayoutManager calculates the real width/height of the components, by looking for how much space they need in order to be resized correctly. So using the 3 methods looks reasonable to me - for example when you want a component to have only a certain size and let another component always take the rest.
So why is using setXXXSize() so discouraged?
There are a lot of good answers on the linked duplicate (Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?).
Adding to the reasons why: With few exceptions, if you are using these methods you are probably fine-tuning your GUI to look good on a specific look-and-feel (and with your system-specific settings, e.g. your preferred desktop font, etc.). The methods themselves aren't inherently evil, but the typical reasons for using them are. As soon as you start tuning pixel positions and sizes in a layout you run the risk of your GUI breaking (or at minimum, looking bad), on other platforms.
As an example of this, try changing your application's default look-and-feel. Even just with the options available on your platform, you will no doubt be surprised at how poorly the results can be rendered.
So, in the name of keeping your GUI functional and nice-looking on all platforms (remember, one of the major benefits of Java is its cross-platformness), you should rely on layout managers, etc., to automatically adjust the sizes of your components so that it renders correctly outside of your specific development environment.
All that said, you can certainly conceive of situations where these methods are justified. Again, they aren't inherently evil, just make sure you are aware of the high potential for complications when you use them, and always try and think if there is another look-and-feel-independent solution to your problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With