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

IchBinKeinBaum picture IchBinKeinBaum · Jun 3, 2012 · Viewed 15.4k times · Source

I read some posts here and I started why some people do

@Override
public Dimension getPreferredSize() {
    return new Dimension(500, 500);
}

instead of

setPreferredSize(new Dimension(500, 500));

Isn't the second one better because it creates only one Dimension object whereas the first one possibly creates several (even if it's not that much wasted memory)? Or am I wrong? Is there a difference at all?

Answer

wattostudios picture wattostudios · Jun 3, 2012

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 500x500. 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 500x500. 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.