Use of overriding getPreferredSize() instead of using setPreferredSize() for fixed size Components

A big difference is how the value can change over time, and so the one you choose should be dependent on what you’re wanting to do with the code.

If you simply call setPreferredSize(new Dimension(500, 500)); in your code, it will do as you expect – it sets the preferred size to 500×500. However, other code in your application can potentially overwrite this value with a new one – anything can call setPreferredSize() and the last call to this method will be the end result.

However, if you override the getPreferredSize() method in your code, it will always return 500×500. It doesn’t matter if any of your code calls the setPreferredSize() method, because they are effectively ignored. If you also override getMinimumSize() and getMaximumSize(), you can force a fixed size on a component that shouldn’t change regardless of the size of the window and the other components.

However, as mentioned by @Andrew Thompson in the comments, this isn’t guaranteed as some layout managers can choose to ignore these, especially if you’re writing your own layout manager, and adding a custom component to some parent containers will also ignore these methods, depending on where/how the component is used. Regardless, it’s still more rigid than calling setPreferredSize() which can easily be called by other code and be totally overwritten.

I also override the getPreferredSize() method (plus getMinimumSize() and getMaximumSize()) for any of my custom components, such as a color picker that needs to have specific dimensions for the component to be painted properly. Without overriding these methods, the Swing layout managers don’t understand how your custom component can be positioned and sized appropriately for the size of the JFrame or JPanel.

Leave a Comment