First of all: Adding an @Override
annotation to your setPrefferedSize
method would have made clear that it should be called setPreferredSize
.
Apart from that, the getPreferredSize
and setPreferredSize
methods have some special semantics in a JComponent
. Quoting from the JComponent#getPreferredSize documentation:
If the preferredSize has been set to a non-null value just returns it. If the UI delegate's getPreferredSize method returns a non null value then return that; otherwise defer to the component's layout manager.
When setting the preferred size with setPreferredSize
, everything is fine. (I'd not recommend to create a subclass of a component only to call some set...
methods in the constructor, but I assume that you'll have some additional methods that will justify extending the class).
However, when overriding getPreferredSize
of JComponent
, one should try to preserve the semantics of this method. That means that you should rather override it like that
@Override
public Dimension getPreferredSize()
{
// If the preferred size was set manually, return this
// size in order to be in line with the specification
// that is described in the JavaDoc
if (super.isPreferredSizeSet())
{
return super.getPreferredSize();
}
// Otherwise, return "your" preferred size. The
// DEFAULT_WIDTH and DEFAULT_HEIGHT would be 20,20
// in your case
return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
(actually, one would have to first ask the UI for a preferred size, but this is probably not desired here)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…