I always see advices in this site of overriding getPreferredSize()
instead of using setPreferredSize()
as shown in these previous threads for example.
- Use of overriding getPreferredSize() instead of using setPreferredSize() for fixed size Components
- Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
- Overriding setPreferredSize() and getPreferredSize()
See this example:
public class MyPanel extends JPanel{
private final Dimension dim = new Dimension(500,500);
@Override
public Dimension getPreferredSize(){
return new Dimension(dim);
}
public static void main(String args[]){
JComponent component = new MyPanel();
component.setPreferredSize(new Dimension(400,400));
System.out.println(component.getPreferredSize());
}
}
setPreferredSize()
- Sets the preferred size of this component.
getPreferredSize()
- 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.
So doing this clearly breaks Liskov Substitution Principle.
prefferedSize
is a bound property so when you set it a firePropertyChange
is executed. So my question is when you override getPrefferedSize()
don't you need to override setPreferredSize(..)
too?
Example:
public class MyPanel extends JPanel{
private Dimension dim = null;
@Override
public Dimension getPreferredSize(){
if(dim == null)
return super.getPreferredSize();
return new Dimension(dim);
}
@Override
public void setPrefferedSize(Dimension dimension){
if(dim == null)
dim = new Dimension(500,500);
super.setPreferredSize(this.dim); //
}
public static void main(String args[]){
JComponent component = new MyPanel();
component.setPreferredSize(new Dimension(400,400));
System.out.println(component.getPreferredSize());
}
}
Now we see that we get identical results but listeners will get notified with real values and besides we don't break LSP cause setPreferredSize
states Sets the preferred size of this component.
but not how.
lsp
perhaps making ourinmutableSizeComponent
and throwing not supporting exception – Confrere